SlideShare a Scribd company logo
SmartDSP Operating
            System

                        User Guide




Revised: 14 June 2011
Freescale, the Freescale logo, CodeWarrior, PowerQUICC, and StarCore are trademarks of Freescale Semiconductor,
Inc., Reg. U.S. Pat. & Tm. Off. Processor Expert, QorIQ, and QUICC Engine are trademarks of Freescale Semiconduc-
tor, Inc. All other product or service names are the property of their respective owners.
© 2009—2011 Freescale Semiconductor, Inc. All rights reserved.
Information in this document is provided solely to enable system and software implementers to use Freescale Semicon-
ductor products. There are no express or implied copyright licenses granted hereunder to design or fabricate any inte-
grated 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 partic-
ular 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 dam-
ages. “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 “Typ-
icals”, 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 de-
signed, 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 Semi-
conductor product could create a situation where personal 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.



                                       How to Contact Us

  Corporate Headquarters               Freescale Semiconductor, Inc.
                                       6501 William Cannon Drive West
                                       Austin, TX 78735
                                       U.S.A.

  World Wide Web                       http://www.freescale.com/codewarrior

  Technical Support                    http://www.freescale.com/support
Table of Contents
1   Introduction                                                                                                                    9
           Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
           Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
               Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
               Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
               Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
               Network Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
               Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
           Directory Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
           Initialization and Start Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
           SmartDSP OS Linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
               Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
               Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
           Guide to the CodeWarrior Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
           More About SmartDSP OS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

2   Kernel Components                                                                                                            25
           Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
               Interrupt Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
               Interrupt Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
           Scheduler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
           Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
               Task States. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
               Background Task. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
           Spinlocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
           Memory Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
               Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
               Buffer Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
           Memory Management Unit (MMU) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
               MMU Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
               MMU Segment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
               MMU Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53


SmartDSP OS User Guide                                                                                                               3
Table of Contents


              MMU Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55
              MMU Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56
          Caches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57
              Cache Sweep Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57
              Configuration of Caches in SmartDSP OS . . . . . . . . . . . . . . . . . . . . . . . . . .58
          Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59
          Intercore Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62
              Configuration of Intercore Messaging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63
          Intercore Message Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66
              Configuration of Intercore Message Queues in SmartDSP OS . . . . . . . . . . .66
              Intercore Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67
          Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68
              Event Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .69
              Event Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71
          OS Tick Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73
              Configuration of OS Tick Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73
          Software Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74
              Configuration of Software Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .75
          Hardware Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .78
              Configuration of Hardware Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79

3   Hardware Abstraction Layers (HAL)                                                                                         81
          HAL in SmartDSP OS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81
             Conceptual Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81
             Conceptual Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .83
          Buffered I/O (BIO) Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .83
             BIO Layers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .84
             BIO Initialization Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .84
             BIO Runtime Workflow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .87
          Coprocessor (COP) Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .88
             COP Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89
             COP Initialization Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89
             COP Runtime Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90
          Synchronized I/O (SIO) Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91
             SIO Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91

4                                                                                           SmartDSP OS User Guide
Table of Contents


              SIO Initialization Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
              SIO Runtime Workflow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
           Character I/O (CIO) Module. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
              CIO Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
              CIO Initialization Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
              CIO Runtime Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

4   Drivers                                                                                                                   99
           Direct Memory Access (System DMA) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
              Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
              Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
              Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
              Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
              Resource Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
              Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
           OCeaN DMA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
              Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
              Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
              Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
           QUICC Engine Unified Ethernet Controller (QE UEC). . . . . . . . . . . . . . . . . . 115
              Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
              Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
              Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
              Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
              Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
              Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
           Serial RapidIO (sRIO) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
              Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
              Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
              Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
              Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
              Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
              Resource Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
              Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
           Doorbell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138

SmartDSP OS User Guide                                                                                                           5
Table of Contents


             Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138
             Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138
             Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139
             Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139
             Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141
          PCI Express (PCIe) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141
             Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141
             Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .142
             Data Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .144
             Resource Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .149
             Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .149
          Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) . . . . . . . . . . .150
             Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .150
             Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .150
             Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151
             Data Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .152
             Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155
             Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .164
          RIONET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .164
             Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .164
             Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .165
             Data Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .166
             Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .168
             Resource Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177
             Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177
          Time Division Multiplexing (TDM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177
             Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177
             Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .178
             Data Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .178
             Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .179
             Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .179
          Universal Asynchronous Receiver/Transmitter (UART). . . . . . . . . . . . . . . . . .179
             Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .179
             Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .180
             Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .180

6                                                                                        SmartDSP OS User Guide
Table of Contents


                UART Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
                Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
                Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
                Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

5   Network Stack                                                                                                         183
           Net Stack in SmartDSP OS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
              Conceptual Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
              Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
              Compile-time Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
           Supported Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
           IPv6 Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
              Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
              Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
              Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
              Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
              Demo Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
              Appendix Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
              Dynamic Host Control Protocol (DHCP) . . . . . . . . . . . . . . . . . . . . . . . . . . 194
              Real-time Transport Protocol (RTP) or Secure Real-time Transport Protocol
                  (SRTP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
              Real-time Transport Control Protocol (RTCP) . . . . . . . . . . . . . . . . . . . . . . 198
              Uniform Data Packet (UDP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
              Transmission Control Protocol (TCP). . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
              Internet Control Message Protocol (ICMP) . . . . . . . . . . . . . . . . . . . . . . . . 205
              Internet Protocol (IP). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
              IP Security (IPSec) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
              Address Resolution Protocol (ARP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
              Management Information Base (MIB) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220

6   Enabling Software                                                                                                     221
           Kernel Awareness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
              Using SmartDSP OS Kernel Awareness Tool . . . . . . . . . . . . . . . . . . . . . . . 222
              Viewing KA Logs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
           Enablement Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238

SmartDSP OS User Guide                                                                                                          7
Table of Contents


                SmartDSP HEAT Runtime Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .238
                SmartDSP HEAT Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .239
                eCLI Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .240

7   Utilities                                                                                                            247
           Verification and Stimulus Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .247
              IP UDP Generator Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .247
              Real-time Transport Protocol (RTP) Player Utility . . . . . . . . . . . . . . . . . . .248
              libSRTP Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .254
              MJPEG Player Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .255
              CommExpert Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .257

A Using C++ with SmartDSP OS                                                                                             269

Index                                                                                                                    271




8                                                                                         SmartDSP OS User Guide
1
Introduction
           The SmartDSP Operating System (OS) is a Real Time Operating System (RTOS) that, in
           addition to providing drivers for the MSBA8100 processor, also runs on the following
           StarCore DSP-based processors:
             • MSC8101
             • MSC812x
             • MSC814x
             • MSC815x/MSC825x
           The StarCore CodeWarrior (CW) Development Studio includes SmartDSP OS royalty-
           free source code. Further, SmartDSP OS has a high-level Application Programming
           Interface (API) that lets users develop integrated applications for StarCore processors.
           This chapter provides information about SmartDSP OS—its features, architecture, startup
           processes and more.
             • Features
             • Architecture
             • Directory Structure
             • Initialization and Start Up
             • SmartDSP OS Linker
             • Guide to the CodeWarrior Documentation
             • More About SmartDSP OS


Features
           In SmartDSP OS, most functions are written in ANSI C. However, when needed,
           Assembly optimizes time-critical functions by maximizing StarCore’s multiple execution
           units.
           Other SmartDSP OS features include the following:
             • small memory footprint ideal for high-speed StarCore processors
             • priority-based event-driven scheduling (triggered by user applications or HW)
             • dual-stack pointer for exception and task handling
             • inter-task communication using queues, semaphores, and events.

SmartDSP OS User Guide                                                                                9
Introduction
Architecture


Architecture
               SmartDSP OS design is Cooperative Asymmetric Multi-Processing (CAMP)-based:
                 • cores run their own OS instances; and,
                 • OS manages shared resources and supports inter-core communication.
               SmartDSP OS also provides an SMP scheduler for MSC814x and MSC815x architectures.
               The following sections explain different components of SmartDSP OS architecture:
                 • Platforms
                 • Kernel
                 • Drivers
                 • Network Stack
                 • Utilities


               Platforms
               Table 1.1 lists SmartDSP OS-supported platforms.
Table 1.1 SmartDSP OS-supported Platforms

                Platform                                    Specific Targets

                MSC815x/MSC825x                               • MSC8158/MSC8157
                                                              • MSC8156/MSC8154/
                                                                MSC8152/MSC8151
                                                              • MSC8256/MSC8524/
                                                                MSC8252/MSC8251

                MSC814x                                       • MSC8144
                                                              • MSC8144E
                                                              • MSC8144EC

                MSC812x                                       • MSC8122
                                                              • MSC8126
                                                              • MSC8102

                MSC810x                                       • MSC8101
                                                              • MSC8103

                MSBA8100                                    Supported via MSC8144 libraries




10                                                                       SmartDSP OS User Guide
Introduction
                                                                                      Architecture


           Kernel
           The SmartDSP OS kernel is well-suited for multi-core processors and applications. The
           kernel has these features:
             • supports HW and SW interrupts
             • supports spinlocks to protect critical multicore data
             • allows user-defined interrupt handlers
             • Memory Management Unit (MMU) supports HW memory protection


           SmartDSP OS kernel components:
             • Caches
             • Hardware Abstraction Layer (HAL)
             • Inter-core messaging
             • Interrupts (HW, SW, and virtual)
             • MMU
             • Memory Manager
             • Message and event queues
             • Scheduler
             • Semaphores
             • Spinlocks
             • SW and HW timers
             • Tasks


           Drivers
           The SmartDSP OS provides a unified cross-device API for the support of generic HW
           drivers. Further, it supports drivers providing HW support for relevant Systems-on-a-
           Chip (SoC):
             • Direct Memory Access (DMA)
             • On-chip Network DMA (OCeaN DMA)
             • Ethernet
                – TSEC
                – Quick Engine (UEC)
             • Serial Rapid Input/Output (sRIO)
                – RIONET


SmartDSP OS User Guide                                                                             11
Introduction
Architecture

                    – Doorbells
                    – eMSG
                 • PCI Express (PEX)
                 • MAPLE
                 • Time Division Multiplexing (TDM)
                 • I2C or Generic I2C
                 • SPI or Generic SPI
                 • Universal Asynchronous Receiver/Transmitter (UART)
                 • Direct Slave Interface (DSI)
                 • CPRI
                 • SEC

               NOTE       An SoC is an integrated circuit (IC) containing a core processor, special
                          function processors, multiple memories and buses, standards-based
                          peripherals, custom logic, and mixed-signal components. Together, these
                          features communicate over a dedicated communication infrastructure.



               Network Stack
               The SmartDSP OS has its own network stack that is used by applications to communicate
               with other applications or devices.
               The SmartDSP OS network stack supports these protocols:
                 • Address Resolution Protocol (ARP)
                 • Dynamic Host Configuration Protocol (DHCP)
                 • Internet Control Message Protocol (ICMP)
                 • Internet Control Message Protocol (ICMP) IPv6
                 • Internet Protocol v4 (IPv4)
                 • Internet Protocol v6 (IPv6)
                 • IP Security (IPSec)
                 • Neighbor Discovery
                 • Real-time Transport Protocol (RTP) or Secure RTP (SRTP)
                 • RTP Control Protocol (RTCP) or Secure RTCP (SRTCP)
                 • Transmission Control Protocol (TCP)
                 • Trivial File Transfer Protocol (TFTP)


12                                                                         SmartDSP OS User Guide
Introduction
                                                                                     Directory Structure

                • User Datagram Protocol (UDP)


             Utilities
             The SmartDSP OS provides utilities used to develop applications for StarCore processors:
Table 1.2 Utilities

               Utility                                   Function

               Configuration tool                        Configures SmartDSP OS (os_config.h).

               UDP/IP packet generator                   Create UDP/IP random packets (with
                                                         customizable parameters).

               SRTP client/server

               MJPEG player                              Supports motion JPEG modules.

               RTP player                                Support RTP modules.

               SmartDSP Host Exchange over               Supports Ethernet remote file access.
               Asynchronous Transfer (HEAT)
               server

               CommExpert                                Generates initialization code for supported
                                                         DSPs.



Directory Structure
             The SmartDSP OS is part of the StarCore CodeWarrior Development Studio and is found
             in the directory, StarCore_SupportSmartDSP.
             Table 1.3 lists SmartDSP subdirectories.

Table 1.3 SmartDSP Subdirectories

               Subdirectory                             Content

               demos                                    Sample projects for supported platforms.

               drivers                                  C source and header files for compiling a driver
                                                        library.

               include                                  C header files used by SmartDSP OS
                                                        components.




SmartDSP OS User Guide                                                                                     13
Introduction
Initialization and Start Up

Table 1.3 SmartDSP Subdirectories

                Subdirectory                          Content

                initialization                        C source and header files used for OS
                                                      initialization.

                lib                                   Compiled libraries used by SmartDSP OS
                                                      components.

                source                                C source and header files for building compiled
                                                      libraries.

                tools                                 Utilities provided by SmartDSP OS,

                doc                                   OS documentation files and device-specific
                                                      documentation.



Initialization and Start Up
              The SmartDSP OS uses a specified sequence of function calls during initialization.
Table 1.4

                Initialization Stage                       Description

                Environment Initialization                 1. CW startup file begins execution.
                                                           2. Calls SmartDSP OS hooks, global
                                                           variables, and MMU.
                                                           3. Jumps to application’s main() function.
                                                              • Based on the SmartDSP OS
                                                                option, select from the Build
                                                                Settings page.
                                                              • SmartDSP OS linker files are
                                                                included in a project. See
                                                                Initialization for more
                                                                information.

                SmartDSP OS Initialization                 Main() function calls osInitialize() function.




14                                                                        SmartDSP OS User Guide
Introduction
                                                        Initialization and Start Up

Table 1.4

            Initialization Stage         Description

            Application Initialization    • Main() function initializes user
                                            application.
                                          • Sample applications, under the
                                            demo directory, use appInit().

            Application Startup           • Main() function starts user
                                            application.
                                          • Creates background task in
                                            osStart() function.
                                          • Switches to pending task with
                                            the highest priority.




SmartDSP OS User Guide                                                          15
Introduction
SmartDSP OS Linker


SmartDSP OS Linker
           This section details Initialization and Guidelines.


           Initialization
           Table 1.5 describes the SmartDSP OS linker files that are included in your project if you
           select the option to include SmartDSP OS in the new project wizard.

Table 1.5 SmartDSP OS Linker Files

               File Type                         Linker Files                      Description

               Application-dependant             memory_map_link.l3k               Splits memory
                                                                                   into local/
                                                                                   shared regions.

                                                 local_map_link.l3k                Maps local
                                                                                   sections to the
                                                                                   memory.

                                                 os_msc815x_link.l3k               Primary
                                                                                   application-
                                                                                   dependent file.

               SmartDSP OS MSC815x-              os_msc815x_link_mmu_def           SC3850 MMU
               specific                          ines.l3k                          attribute
                                                                                   definitions

                                                 os_msc815x_link_defines           MSC815x
                                                 .l3k                              internal memory
                                                                                   map

                                                 os_msc815x_link_app.l3k           SmartDSP OS
                                                                                   segment
                                                                                   attribute
                                                                                   definitions

                                                 os_msc8156_linker_ads_d           ADS (DDR)
                                                 efines.l3k                        memory map




           NOTE        See the following guides for information on linker error messages and
                       troubleshooting:




16                                                                     SmartDSP OS User Guide
Introduction
                                                                              SmartDSP OS Linker

                      – StarCore SC3000 Linker User Guide for sc3000-ld linker (.l3k)
                      – StarCore SC100 Linker User Guide for sc100-ld linker (.lcf)



           Guidelines
           This section lists guidelines for using StarCore Linker:
           1. Consider the following if modifying the physical location of local and shared data.
              a. Consider performance issues; e.g., local_non_cacheable is currently in M2
                 memory.
              b. Check that program sections—used during initialization (before and during MMU
                 programming)—maintain 1x1 virtual-to-physical mapping.
              c. Ensure that the segments .att_mmu, .oskernel_local_data, and
                 .oskernel_local_data_bss are all local per core and confined by
                 symbols _VirtLocalData_b, _LocalData_size, and _LocalData_b
                 (memory_map_link.l3k). Symbols initialize the MMU and the stack thus
                 enabling C code to run properly.
           2. Consider the following if there is insufficient space in a specific memory location.
              a. Check if all allocated space is truly required.
              b. Check if there is a memory space or MMU alignment issue.
                  Re-align MMU by modifying the linker command file such that larger sections/
                  segments link first; this provides better aligned base addresses.
              c. Check if memory is truly lacking. If so, move non-critical portions to a distant
                 memory.
           3. SmartDSP OS uses on-chip memory by default.
              • DDR is not essential on a board.
              • If necessary, a portion of the OS can be moved to the DDR.
           4. Changes to the linker command file:
              • If the debugger is still unable to reach the main()function, then there may be an
                issue of insufficient space at a specific memory location.
           5. Memory allocated from a SmartDSP OS-managed heap:
              • May provide better linking flexibility.
           6. Global variables:
              • If not set in a specific section then they will be placed in .data or .bss.
           7. Asymmetric linking (supporting device):
                  • Allows symbols to be linked to sections yet unmapped by all cores.



SmartDSP OS User Guide                                                                               17
Introduction
Guide to the CodeWarrior Documentation

                   • Allows cores to link symbols to different physical memories and/or
                     implementations


Guide to the CodeWarrior Documentation
            Following table provides a guide to the documentation included in the CodeWarrior for
            StarCore DSPs product. The table’s first column identifies a document’s type:
            Getting Started, User Guide, or Application Note.
            For late-breaking information about new features, bug fixes, known problems, and
            incompatibilities, read the release note, which is in this folder: installDirSC

            NOTE       All the information in the PDFs is duplicated in the IDE’s online help. To
                       display online help, start the IDE and select Help > Help Contents.


Table 1.6 Guide to the CodeWarrior Documentation

 Document    Document Name        Description                         PDF Name
 Type

                                  PDF Location: installDirSC

 Getting     CodeWarrior for      Explains how to install the         Quick Start
 Started     StarCore DSPs -      CodeWarrior software on a           for StarCore DSPs.pdf
             Windows Edition      Windows PC
             Quick Start

 Getting     Installing Service   Explains how to install a service   Service Pack Updater
 Started     Pack for             pack or an update for your          Quick Start.pdf
             CodeWarrior          CodeWarrior software running
             Tools - Quick        on the Windows platform.
             Start

 Getting     CodeWarrior          Explains how to convert a           CodeWarrior
 Started     Project Importer     classic CodeWarrior project         Project Importer
             Quick Start          into an Eclipse IDE project         Quick Start.pdf

 Getting     Targeting the        Explains how to set up the          Quick Start for
 Started     MSC8157ADS           MSC8157ADS board, install           MSC8157ADS.pdf
             Board - Quick        CodeWarrior Development
             Start                Studio, and use this software to
                                  create, build, and debug a
                                  simple project that targets this
                                  board.




18                                                                      SmartDSP OS User Guide
Introduction
                                                        Guide to the CodeWarrior Documentation

Table 1.6 Guide to the CodeWarrior Documentation (continued)

 Document   Document Name       Description                         PDF Name
 Type

 Getting    Targeting the       Explains how to install             Quick Start for
 Started    MSC8157ISS          CodeWarrior Development             MSC8157ISS.pdf
            Simulator - Quick   Studio and use this software to
            Start               create, build, and debug a
                                simple project that targets the
                                MSC8157ISS simulator.

 Getting    Targeting the       Explains how to install the         Quick Start
 Started    MSC8156ADS          CodeWarrior software, prepare       for MSC8156ADS.pdf
            Board -             the MSC8156ADS board, and
            Quick Start         then create, build, and run a
                                simple MSC8156 project

 Getting    Targeting the       Explains how to install the         Quick Start
 Started    MSC8156ISS          CodeWarrior software and how        for MSC8156ISS.pdf
            Simulator -         to use this software to create,
            Quick Start         build, and run a simple
                                MSC8156 project

 Getting    Targeting the       Explains how to install the         Quick Start
 Started    MSC8154ADS          CodeWarrior software, prepare       for MSC8154ADS.pdf
            Board -             the MSC8154ADS board, and
            Quick Start         then create, build, and run a
                                simple MSC8154 project

 Getting    Targeting the       Explains how to install the         Quick Start
 Started    MSC8144ADS          CodeWarrior software, prepare       for MSC8144ADS.pdf
            Board -             the MSC8144ADS board, and
            Quick Start         then create, build, and run a
                                simple MSC8144 project

 Getting    Targeting the       Explains how to set up the          Quick Start for P2020-
 Started    P2020-8156 AMC      P2020-8156 AMC board, install       8156 AMC.pdf
            Board - Quick       CodeWarrior Development
            Start               Studio, and use this software to
                                create, build, and debug a
                                simple project that targets the
                                MSC8156 side of this board.

 Getting    Multicore Trace     Exlpains how to collect trace       Quick Start for
 Started    and Profiling of    data on multiple cores of a         Multicore Tracing.pdf
            an MSC8156          project after creating, building,
            Target - Quick      and running a project on an
            Start               MSC8156 target.



SmartDSP OS User Guide                                                                       19
Introduction
Guide to the CodeWarrior Documentation

Table 1.6 Guide to the CodeWarrior Documentation (continued)

 Document    Document Name        Description                        PDF Name
 Type

 Getting     Using the            Explains how to set up the         Ethernet TAP
 Started     Ethernet TAP         Ethernet TAP probe and create,     Quick Start.pdf
             Probe -              build, and debug a simple
             Quick Start          StarCore project that uses this
                                  device.

 Getting     CodeWarrior IDE      Introduces the interface of the    Eclipse Quick
 Started     -Quick Reference     Eclipse-based CodeWarrior          Reference Card.pdf
             Card                 IDE and provides a quick
                                  reference to its key bindings

                             PDF Location: installDirSCHelpPDF

 User        CodeWarrior for      Provides answers to the most       StarCore FAQ Guide.pdf
 Guide       StarCore DSPs -      frequently asked questions
             Frequently Asked     about the CodeWarrior IDE and
             Questions            the StarCore build tools.

 User        Freescale Eclipse    Documents Freescale’s general      Freescale Eclipse
 Guide       Extensions Guide     extensions to the Eclipse IDE.     Extensions Guide.pdf
                                  NOTE: This document may
                                  describe features that are not
                                  available in the CodeWarrior for
                                  StarCore DSPs product;
                                  further, the figures show a
                                  typical user interface, which
                                  may differ slightly from that of
                                  the StarCore product.

 User        StarCore DSPs        Documents the StarCore-            Targeting
 Guide       Targeting Manual     specific features of your          StarCore DSPs.pdf
                                  CodeWarrior product

 User        StarCore             Explains how to use runsim and     StarCore Simulator
 Guide       Simulator            the StarCore simulators to:        User Guide.pdf
             User Guide           develop software, profile code,
                                  and perform speed and size
                                  tradeoff analyses

 User        Profiling and        Documents the CodeWarrior          Profiling and Analysis
 Guide       Analysis             Profiling and Analysis tools,      Users Guide.pdf
             User Guide           which provide visibility into an
                                  application as it runs on the
                                  simulator or hardware




20                                                                     SmartDSP OS User Guide
Introduction
                                                    Guide to the CodeWarrior Documentation

Table 1.6 Guide to the CodeWarrior Documentation (continued)

 Document   Document Name     Description                       PDF Name
 Type

 User       StarCore ABI      Defines a set of standards for    StarCore ABI
 Guide      Reference         ensuring interoperability         Reference Manual.pdf
            Manual            between conforming
                              CodeWarrior for StarCore
                              software components, such as,
                              compilers, assemblers, linkers,
                              debuggers, and assembly
                              language code

 User       StarCore          Documents the StarCore            StarCore C-C++ Compiler
 Guide      C/C++ Compiler    C/C++ compiler                    User Guide.pdf
            User Guide

 User       StarCore          Documents the intrinsic           StarCore C-C++ Compiler
 Guide      C/C++ Compiler    functions the StarCore C/C++      Intrinsics Reference
            Intrinsics        compiler provides.                Manual.pdf
            Reference
            Manual

 User       EWL C             Documents the Embedded            EWL C Reference.pdf
 Guide      Reference         Warrior C Library, Freescale’s
                              ANSI-compliant implementation
                              of the C standard library

 User       EWL C++           Documents the Embedded            EWL C++ Reference.pdf
 Guide      Reference         Warrior C++ Library,
                              Freescale’s ANSI-compliant
                              implementation of the C++
                              standard library

 User       StarCore          Documents the StarCore            StarCore Assembler
 Guide      Assembler User    assembler                         User Guide.pdf
            Guide

 User       StarCore          Documents the StarCore            StarCore SC3000 Linker
 Guide      Linker (SC3000)   SC3000 linker, the default        User Guide.pdf
            User Guide        linker for MSC8156 device.
                              SC3000 linker command files
                              have the .l3k extension.

 User       StarCore          Documents the StarCore            StarCore SC100 Linker
 Guide      Linker (SC100)    SC100 linker. SC100 linker        User Guide.pdf
            User Guide        command files have the .lcf
                              extension.



SmartDSP OS User Guide                                                                    21
Introduction
Guide to the CodeWarrior Documentation

Table 1.6 Guide to the CodeWarrior Documentation (continued)

 Document      Document Name        Description                        PDF Name
 Type

 User          SmartDSP OS          Explains how to develop            SmartDSP OS Concepts
 Guide         User Guide           programs for the SmartDSP OS       User Guide.pdf

 User          SmartDSP OS          Documents the SmartDSP OS          SmartDSP OS API
 Guide         API Reference        API — the functions, structures,   Reference Manual.pdf
               Manual               and classes used in
                                    SmartDSP OS programs

 User          Ethernet TAP         Explains how to use the            Ethernet TAP
 Guide         User Guide           Ethernet TAP probe                 Users Guide.pdf

 User          USB TAP              Explains how to use the            USB TAP Users Guide.pdf
 Guide         User Guide           USB TAP probe

 Application   AN3436 -             Explains how to verify boot over   AN3436.MSC81xx Ethernet
 Note          MSC81xx              Ethernet for the MSC8144           Boot Test.pdf
               Ethernet Boot
               Test

 Application   AN3788 -             Explains how to use the            AN3788.SC.Compiler
 Note          Overlay Support      StarCore compiler’s support for    Overlay Support.pdf
               in StarCore          overlays and includes some
               Compiler             example tool configurations

 Application   AN3899 -             Explains how to use an             AN3899.MSC8156 SC3000
 Note          Using the            SC3000 linker control file (LCF)   LCF.pdf
               SC3000 Linker        to define the memory layout for
               Control File for     applications that run on the
               MSC8156              MSC8156 device
               Applications

 Application   AN4099 -             Explains how to use your           AN4099.Gearshift
 Note          Setting              CodeWarrior tools to set           Points.pdf
               GearShift Points     GearShift points

 Application   AN4108 -             Explains how to create a           AN4108.Config
 Note          Creating a Project   CodeWarrior project that treats    CodeWarrior IDE for
               that Treats an       an MSC8156ADS board as if it       MSC8156 Deriv.pdf
               MSC8156ADS as        contained an MSC8154 or
               if Populated by an   MSC825x variant of the
               MSC8154 or           MSC8156
               MSC825x




22                                                                       SmartDSP OS User Guide
Introduction
                                                                          More About SmartDSP OS

Table 1.6 Guide to the CodeWarrior Documentation (continued)

 Document       Document Name       Description                       PDF Name
 Type

 Application    AN4120 -            Explains how to tune existing C   AN4120.Tuning C Code for
 Note           Tuning C            code for optimal performance      SC DSPs.pdf
                Language Source     on Freescale StarCore-based
                Code for the        DSPs and platforms.
                StarCore DSP




More About SmartDSP OS
               SmartDSP is the chosen OS for Freescale's highly optimized SW libraries—libraries
               supporting baseband, video, voice and other DSP applications.
               Freescale and its SW partners—by offering a wide variety of SW libraries optimized on
               FSL's DSP platforms—enable efficient product development. The SW libraries support
               both up-to-date and legacy voice and video codecs.
               Included in the SW libraries are optimized baseband kernel libraries. SmartDSP OS is
               based on optimized kernels; their unique FSL DSP capabilities enable users to develop
               highly effective SW applications.
               All DSP libraries are implemented on SmartDSP OS—to make use of its rich feature set
               while maintaining expected levels of efficiency and performance.
               For more information on Freescale DSP SW libraries, visit www.freescale.comdsp.




SmartDSP OS User Guide                                                                                 23
Introduction
More About SmartDSP OS




24                       SmartDSP OS User Guide
2
Kernel Components
           An OS kernel is an interface between user applications and HW components. The
           SmartDSP OS kernel has these features:
             • Predictable and realtime oriented as it is comprised of a preemptive, priority-based,
               single core with an event-driven scheduler.
             • Provides interrupt handling, memory management, and task scheduling.
             • Allows both user and OS code to be executed in HW and SW interrupts, and tasks.
             • Supports a dual-stack pointer—it uses both exception and normal stack StarCore
               pointer registers.
             • Supports multi-core by executing an SDOS instantiation on each core and allowing
               inter-core communication and synchronization.
             • Provides an API and functionality for most DSP core and DSP subsystem
               components.
           This chapter details the following SmartDSP OS kernel components.
             • Interrupts
             • Scheduler
             • Tasks
             • Spinlocks
             • Memory Manager
             • Memory Management Unit (MMU)
             • Caches
             • Queues
             • Intercore Messaging
             • Intercore Message Queues
             • Events
             • OS Tick Timers
             • Software Timers
             • Hardware Timers




SmartDSP OS User Guide                                                                            25
Kernel Components
Interrupts


Interrupts
             An interrupt triggers a new event while an interrupt handler executes and services an
             interrupt request. An SoC can have multiple levels of interrupt concentrators; the kernel
             program them during application bring-up and runtime. For example,
               • MSC8101, MSC812x — GIC, LIC, and PIC
               • MSC814x, MSC815x — GCR and EPIC
             SmartDSP OS uses the ESP stack pointer for interrupt handling.
             SC processor interrupts are either MI or NMI:
               • MI
                  – Application can ignore the interrupt request.
                  – Priorities can vary between interrupt sources.
               • NMI
                  – Interrupt request is critical.
                  – Interrupt handler must execute.
             Consider the following SC interrupt characteristics:
               • StarCore SR calls osStart() from main()to enable interrupts.
               • User NMI ISR should not call OS functions guarded by disabling and enabling
                 interrupts; e.g., osHwiSwiftDisable() and osHwiSwiftEnable().
                  – Prevents data or code corruption.
                  – Based on the broken assumption of atomicity in these code portions—a false
                    assumption in NMI.

             NOTE       Ensure that SoC-level NMIs, such as NMI_B and virtual NMIs, are NOT
                        triggered during kernel initialization [prior to calling osStart()].



             Interrupt Sources
             SmartDSP OS interrupts are primarily generated from a single origin. MSC814x interrupt
             sources include the following:
               • SC3400 core includes trap-generated interrupts (used for SW interrupts), illegal
                 instructions, and debug exceptions.
               • DSP subsystem includes MMU, cache, and timer interrupts.
               • DSP SoC includes peripheral-generated interrupts, VIRQ, and external interrupts
                 lines.



26                                                                        SmartDSP OS User Guide
Kernel Components
                                                                                              Interrupts


           Interrupt Types
           SmartDSP OS kernel supports HWI and SWI interrupts.

           NOTE       An application can define stack size in the os_config.h file using
                      definition, #define OS_STACK_SIZE <size>.

                      An interrupt runs on a dedicated stack, StackStart[].



           Hardware Interrupts
           HW devices such as DMA, OCeaN DMA, and Ethernet controllers can generate HW
           interrupts. In SmartDSP OS kernel, the OS interrupt dispatcher handles HW interrupts in
           one of these ways:
             • Calls an OS interrupt handler.
             • Calls an OS interrupt handler before the interrupt calls a user-defined interrupt
               handler.
             • Calls a user-defined interrupt handler.

           NOTE       OCeaN DMA is the on-chip network DMA. See demosstarcoremsc815xuart
                      for more information.

           HW interrupt characteristics include the following:
             • Every interrupt handler should return void, and receive a single parameter.
             • The received parameter is part of the interrupt registration; it is set at registration
               time.
             • The parameter can act as a global variable pointer; the variable may change over the
               course of an application.
             • Application-provided interrupt handles must be given a HW interrupt function; this
               is allocated upon registering the HW interrupt handle.
             • HW interrupt prototype function:
               typedef void (*os_hwi_function)(os_hwi_arg).
             • HW interrupts are HW platform-specific thus SmartDSP OS kernel contains header
               files specific to given HW platforms. For example,
                – msc814x_hwi.h header file defines HW interrupts for the MSC814x platform.
                – msc815x_hwi.h header file defines HW interrupts for the MSC815x platform.




SmartDSP OS User Guide                                                                                   27
Kernel Components
Interrupts

             SmartDSP OS kernel features include the following:
               • Supports edge and level HW interrupts.
               • MMU exception interrupts are hardwired for edge mode.
               • An application can define edge and level HW interrupts as follows:
                  – #define LEVEL_MODE
                  – #define EDGE_MODE
               • Enables high priority interrupt handlers to finish before low priority interrupt
                 handlers begin executing.
                  – Respectively, parameters OS_HWI_PRIORITY0 and
                    OS_HWI_LAST_PRIORITY specify the highest and lowest priority for HW
                    interrupts.
                  – Number of priorities depends on PIC or EPIC.
               • Interrupt controller is located in the DSP subsystem of these processors:
                  – MSC8101, MSC812x — PIC
                  – MSC814x, MSC815x — EPIC
               • Maximum number of HW interrupt priorities:
                  – SC140-based SoC = 7
                  – SC3400/SC3850-based SoC = 31
                  – See SC3850/SC3400 DSP Core Reference Manual.
             Table 2.1 lists SmartDSP OS HW interrupt module functions.




28                                                                        SmartDSP OS User Guide
Kernel Components
                                                                                              Interrupts


Table 2.1 Functions Available for Hardware Interrupts

              Flow State                         Name                        Description

              Kernel bring up (the user          osHwiInitialize()           Initializes all interrupt
              application does not call these                                handlers to default ones
              functions specifically. Instead,                               and enables all NMI in
              osInitialize() calls these                                     EPIC (where
              functions based on the                                         supported).
              parameters from os_config.h
              and configurations from
              msc81xx_config.c)

              Application bring up               osHwiCreate()               Installs an interrupt
                                                                             handler in the OS
                                                                             dispatcher. It sets the
                                                                             interrupt priority in the
                                                                             interrupt assignment
                                                                             register and enables the
                                                                             interrupt.

              Application tear down              osHwiDelete()               Detaches an interrupt
                                                                             handler from the OS
                                                                             dispatcher.


            Listing 2.1 shows how an application installs a hardware interrupt in the OS dispatcher.
            1. Application calls the kernel interrupt handler, osHwiCreate().
            2. Kernel interrupt handler sets interrupt priority in the interrupt assignment register and
               enables the interrupt.
            See SmartDSP OS API Reference Manual for more information.

Listing 2.1 Installing a HWI in the OS Dispatcher

os_status osHwiCreate(os_hwi_handle hwi_num,
                      os_hwi_priority priority,
                      os_hwi_mode mode,
                      os_hwi_function handler,
                      os_hwi_arg argument);




SmartDSP OS User Guide                                                                                   29
Kernel Components
Interrupts

             Software Interrupts
             A SWI is a program-generated interrupt. SmartDSP OS kernel supports nesting SWIs with
             HWIs and other priority SWIs. Any HWI or high priority SWI preempt a low priority
             SWI.
               • Highest priority SWIs are specified by parameter OS_SWI_PRIORITY0.
               • Lowest priority SWIs are specified by OS_SWI_PRIORITY15.
             An application, using the definition #define OS_TOTAL_NUM_OF_SWI <num> in the
             os_config.h file, can specify the number of SWIs per core.
             The SWI prototype function is
             typedef void (*os_swi_function)(os_swi_count);

             NOTE      An array of SWI handlers is allocated from the OS_MEM_LOCAL heap. There
                       is a memory penalty if too high a value is set.

             Table 2.2 lists SmartDSP OS SWI module functions.

Table 2.2 Available SWI Functions

              Flow State                         Name                    Description

              Kernel bring up (the user          osSwiInitialize()       Initializes the software
              application does not call these                            interrupts module.
              functions specifically. Instead,
              osInitialize() calls these
              functions based on the
              parameters from os_config.h
              and configurations from
              msc81xx_config.c)

              Application bring up               osSwiFind()             Finds the first available
                                                                         software interrupt
                                                                         number.

                                                 osSwiCreate()           Attaches an interrupt
                                                                         handler to a software
                                                                         interrupt.




30                                                                    SmartDSP OS User Guide
Kernel Components
                                                                                              Interrupts

Table 2.2 Available SWI Functions

             Flow State                        Name                          Description

             Application runtime               osSwiActivate()               Activates the given
                                                                             software interrupt.

                                               osSwiCountSet()               Sets the count of the
                                                                             given software interrupt.

                                               osSwiCountInc()               Increments the count of
                                                                             the given software
                                                                             interrupt and activates
                                                                             it.

                                               osSwiCountDec()               Decrements the count
                                                                             of the given software
                                                                             interrupt. This function
                                                                             also activates the
                                                                             software interrupt if the
                                                                             count is zero after the
                                                                             operation.

             Application tear down             osSwiDelete()                 Detaches the given
                                                                             software interrupt from
                                                                             its handler.


            Listing 2.2 shows how to create a SWI using functions osSwiFind() and osSwiCreate().
              • SWI, g_swi_holder1, is generated with the highest priority.
              • An interrupt handler, foo, services the interrupt request.
            Refer to SmartDSP OS API Reference Manual for more information.

Listing 2.2 Creating a SWI

osSwiFind(&g_swi_holder1);
status = osSwiCreate(foo,                                //software interrupt function
                     g_swi_holder1,                       //software interrupt number
                    OS_SWI_PRIORITY0,                    //software interrupt priority
                     50);                                 //user Id
if (status != OS_SUCCESS) OS_ASSERT;
osSwiCountSet(g_swi_holder1, 100);

status = osSwiActivate(g_swi_holder1);
OS_ASSERT_COND(status != OS_SUCCESS);

void foo(os_swi_count count)


SmartDSP OS User Guide                                                                                   31
Kernel Components
Scheduler

{
     uint16_t self;
     if (count != 100) OS_ASSERT;
     status = osSwiSelf(&self);
     if (status != OS_SUCCESS) OS_ASSERT;
     status = osSwiDelete(self);
     if (status != OS_SUCCESS) OS_ASSERT;
}



Scheduler
            A scheduler determines when a specific task or a process must utilize the CPU. In the
            SmartDSP OS kernel, the scheduler is preemptive and event driven; that is, an event, such
            as an interrupt, triggers the scheduler to switch to the next higher priority task or process.
            The SmartDSP OS kernel does not enforce time slots or any other mechanism of load
            balancing.
            In SmartDSP OS, each core has its own scheduler. The scheduler handles the events in this
            priority order:
            1. NMI
            2. HWI
            3. SWI
            4. Tasks
            In other words, the scheduler considers an NMI as the top priority event, and a task as the
            lowest priority event.
            Software interrupts can be activated by hardware interrupts, other software interrupts, and
            by tasks. Software interrupts can be preempted by hardware interrupts or higher-priority
            software interrupts. Hardware and software interrupts can be nested. The idle or
            background task has the lowest priority, and it should never end. It can include user code
            and is preempted by software interrupts as well as hardware interrupts and higher priority
            tasks.
            Figure 2.1 shows an example of how the scheduler operates with a single background task
            in the SmartDSP OS kernel. A higher-priority SWI runs to completion before a lower-
            priority SWI executes. SWIs are preempted by any HWI or a higher-priority SWI.
            Hardware interrupts always have priority over software interrupts. Hardware and software
            interrupts can be nested, and the priorities of each are considered.

Figure 2.1 SmartDSP OS Scheduler Operation




32                                                                         SmartDSP OS User Guide
Kernel Components
                                                                                               Tasks




           In Figure 2.1, the SmartDSP OS Scheduler operates as follows:
           1. A HWI with priority 0 (the highest) activates a SWI with priority 8.
           2. The SWI with priority 8 waits for HWI with priority 0 to finish.
           3. Another HWI with priority 4 is activated as soon as HWI with priority 0 finishes – the
              HWI with priority 4 is scheduled before the pending SWI with priority 8 (all HWI are
              scheduled before SWI).
           4. The HWI with priority 4 begins executing.
           5. The HWI with priority 4 activates another SWI, with priority 6.
           6. SWI with priority 6 is scheduled before the pending SWI with priority 8 (SWI with
              higher priority preempt SWI with lower priority).
           7. The SWI with priority 6 begins executing.
           8. The SWI with priority 8 begins executing after SWI with priority 6 finishes.


Tasks
           A task represents a specific part of a larger program that is currently loaded in memory.
           Each task in the SmartDSP OS kernel has its own:
             • priority.
             • stack and therefore a set of core registers.
             • PID and DID (where supported).
             • name.


SmartDSP OS User Guide                                                                             33
Kernel Components
Tasks

           • private data.
         A task in the SmartDSP OS kernel is:
           • different from SWIs and HWIs because a task has its own context and stack.
           • attached to the core on which it was created.
         The minimum and default number of tasks in the SmartDSP OS kernel is one. An
         application can override this setting in the os_config.h file using this definition:
         #define OS_TOTAL_NUM_OF_TASKS                  <num>
         Tasks cannot be shared between cores or stolen. A task can sleep and/or yield the core. An
         array of task handlers will be allocated off of the OS_MEM_LOCAL heap; therefore you
         should be aware of the memory penalty of defining too many tasks. The
         OS_TASK_PRIORITY_HIGHEST and OS_TASK_PRIORITY_LOWEST parameters
         respectively specify the highest and the lowest priority for tasks. In addition, an
         application can use the following parameters for specifying a priority other than the
         highest and the lowest:
           • OS_TASK_PRIORITY_01,
           • OS_TASK_PRIORITY_02,
           • …
           • OS_TASK_PRIORITY_30
         The maximum number of priorities for tasks is 32. An application can create multiple
         tasks with the same priority that will be scheduled in round-robin.
         The SmartDSP OS kernel implements cooperative and priority-based scheduling among
         tasks. The priority of a task can be changed during run time by calling the
         osTaskPrioritySet() function. This function can be called from any context, HWI, SWI, or
         by another task.
         An application can prohibit the scheduler from switching to a higher priority task by
         locking it. Locking will prevail even if the dispatcher is invoked due to some other event
         such as a HWI. Use these functions to lock and unlock the scheduler, respectively:
           • osTaskSchedulerLock()
           • osTaskSchedulerUnlock()
         The SmartDSP OS kernel assigns each task with a unique program ID (PID) or data ID
         (DID) wherever supported in MMU. However, tasks can share a PID and/or a DID if an
         application specifically adds them to a SmartDSP OS MMU context using these functions:
           • osTaskMmuDataContextSet()
           • osTaskMmuProgContextSet()
         An MMU context defines a PID or DID (depending on the type of context) as well as the
         set of enabled MMU segments. By default, all tasks have the set of segments enabled in
         the system context. A task is not required to belong to the same program and data contexts.


34                                                                     SmartDSP OS User Guide
Kernel Components
                                                                                               Tasks

            For example, task A and B may belong to the same data context while task A and C belong
            to the same program context. This does not require task B and C to share their data
            context.
            Refer to SmartDSP OS API Reference Manual for more information.
            Table 2.3 lists the functions available in the tasks module of the SmartDSP OS.

Table 2.3 Functions Available for Tasks

             Flow State                      Name                        Description

             Kernel bring up (the user       osTasksInitialize()         Allocates a scheduler and
             application does not call                                   then allocates tasks and
             these functions specifically.                               events objects and inserts
             Instead,                                                    them in the scheduler.
             osInitialize() calls
             these functions based on
             the parameters from
             os_config.h and
             configurations from
             msc81xx_config.c)

             Application bring up            osTaskFind()                Retrieves the index of an
                                                                         unused task.

                                             osTaskCreate()              Creates a task. The task
                                                                         is created in the
                                                                         suspended state. Activate
                                                                         the task using
                                                                         osTaskActivate().
                                                                         For the background task,
                                                                         pass a pointer to the task
                                                                         created using
                                                                         osTaskCreate() as an
                                                                         argument to the
                                                                         osStart() function.




SmartDSP OS User Guide                                                                                35
Kernel Components
Tasks

Table 2.3 Functions Available for Tasks (continued)

             Flow State                Name                Description

             Application runtime       osTaskActivate()    Removes the created task
                                                           from the suspend state. If
                                                           the task is not suspended,
                                                           the function has no effect.
                                                           If the task is not delayed
                                                           or pending, it is moved to
                                                           the ready state, and
                                                           scheduler is called. If this
                                                           is the highest priority
                                                           ready task and it is the
                                                           first in its priority queue,
                                                           then it will resume or start.

                                       osTaskSuspend()     Moves the task to the
                                                           suspend state.

                                       osTaskDelay()       Delays the running task
                                                           by blocking the task for
                                                           the specified number of
                                                           ticks.




36                                                        SmartDSP OS User Guide
Kernel Components
                                                                                                Tasks

Table 2.3 Functions Available for Tasks (continued)

             Flow State                    Name                           Description

                                           osTaskYield()                  Schedules a different task
                                                                          in same priority or higher
                                                                          if available. The
                                                                          SmartDSP OS scheduler
                                                                          allows several tasks to
                                                                          have the same priority
                                                                          level. In this case, the
                                                                          tasks should implement
                                                                          cooperative scheduling to
                                                                          allow other tasks to
                                                                          execute first. The
                                                                          osTaskYield() function
                                                                          allows a task to preempt
                                                                          itself in favor of another
                                                                          specific task or next ready
                                                                          task of the same priority.

                                           osTaskPriorityReadyC           Counts the number of
                                           ount()                         tasks that are ready in a
                                                                          specified priority.

                                           osTaskMmuDataContext           Sets a data context for a
                                           Set()                          task. It affects the data
                                                                          MMU segments enabled
                                                                          and the DID.

                                           osTaskMmuProgContext           Sets a program context
                                           Set()                          for a task. It affects the
                                                                          program MMU segments
                                                                          enabled and the PID.

                                           osTaskSchedulerLock(           Locks the scheduler so
                                           )                              that the running task
                                                                          cannot be replaced.

                                           osTaskSchedulerUnloc           Unlocks the scheduler so
                                           k()                            that the running task can
                                                                          be replaced.

             Application tear down         osTaskDelete()                 Deletes a task.


            Listing 2.3 shows how to find an existing task and create a new task using the
            osTaskFind() and osTaskCreate() functions.



SmartDSP OS User Guide                                                                                 37
Kernel Components
Tasks

Listing 2.3 Finding and creating a task

uint8_t task_stack[TASK_STACK_SIZE];

status = osTaskFind(&task_handle);
OS_ASSERT_COND(status == OS_SUCCESS);

os_task_init_param.task_function = F;
os_task_init_param.task_name = N;
os_task_init_param.stack_size = SZ;
os_task_init_param.task_arg = A;
os_task_init_param.task = task_handle;
os_task_init_param.task_priority = OS_TASK_PRIORITY_27;
os_task_init_param.private_data = D2;
os_task_init_param.top_of_stack = S;

/* Stack should be in a memory accessible to the task given its MMU
data context */

status = osTaskCreate(&os_task_init_param);
OS_ASSERT_COND(status == OS_SUCCESS);

            Listing 2.4 shows how to activate and suspend a task using the osTaskActivate() and
            osTaskSuspend() functions.

Listing 2.4 Activating and suspending a task

status = osTaskActivate(task_handle);
OS_ASSERT_COND(status == OS_SUCCESS);

status = osTaskSuspend(task_handle);
OS_ASSERT_COND(status == OS_SUCCESS);

            Use the source code shown in Listing 2.5 to verify the task suspension. The source code
            verifies the task status and deletes the task (using the osTaskDelete() function) if the task
            is suspended. If the task is not suspended, the source code delays the task using the
            osTaskDelay() function.

Listing 2.5 Verifying task suspension

if (osTaskStatusGet(task_handle) & OS_TASK_SUSPEND)
{
    status = osTaskDelete(task_handle);     //Deleting the task
    OS_ASSERT_COND(status == OS_SUCCESS);
}
status = osTaskDelay(DELAY_TIME);           //Delaying the task


38                                                                         SmartDSP OS User Guide
Kernel Components
                                                                                                Tasks

OS_ASSERT_COND(status == OS_SUCCESS);



            Task States
            A task exists in one of these states:
              • Ready
              • Running
              • Blocked
            Figure 2.2 shows how a task transitions from one state to another.

Figure 2.2 Task States




            A task changes its state from one to another when:
              • A task that is ready to run is in a READY state.
              • A ready to run task becomes the highest priority task and starts running, its state
                changes from READY to RUNNING.
              • A higher priority task becomes READY and preempts the current task; the currently
                running task state changes from RUNNING to READY.
              • Another higher priority task suspends a READY task; the suspended task state
                changes from READY to BLOCKED.
              • The task suspends or delays itself; the task state changes from RUNNING to
                BLOCKED.
              • A blocked task gets activated by another task, its delay expires, or a waited event
                occurs; the task state changes from BLOCKED to READY.


SmartDSP OS User Guide                                                                                39
Kernel Components
Tasks

              • A task, by default, is created in a BLOCKED state.
            Figure 2.3 shows how a task state changes from one to another. In this figure, the arrows
            represent the SWI activation by HWI and stars represent events, which may or may not
            immediately trigger their HWI. An idle task is running. A HWI with priority 0 activates a
            SWI with priority 6. The SWI (Priority 6) posts the task on the semaphore, which makes
            the task move from pending to READY state. The task is not yet activated because SWI
            (Priority 6) and SWI (Priority 7) are still running in the system. The READY task
            becomes active only when the higher priority event or HWI or SWI finishes execution.
            Once all the higher priority events finish executing, the scheduler is called and SWI
            returns back to the interrupt dispatcher. This moves the task from READY to RUNNING
            state because it is the highest priority task in the system now.

Figure 2.3 Task States Transition




            Background Task
            The SmartDSP OS kernel requires a task in the background so the system always has at
            least one task running. The last step of OS initialization activates the background task with
            the lowest priority. You do not need to explicitly find or create the background task; it is
            created by the operating system. The background task function pointer is passed as an
            argument to the osStart() function. The background task uses system MMU settings
            (wherever supported). MMU has system data settings and system program settings. The
            background task should not return.
            An application can override the default stack size for the background task in the
            os_config.h file using this definition:



40                                                                        SmartDSP OS User Guide
Kernel Components
                                                                                          Tasks

           #define OS_BACKGROUND_STACK_SIZE               <size>

           NOTE    An application cannot block, suspend, or delete the background task at any
                   stage during execution.




SmartDSP OS User Guide                                                                          41
Kernel Components
Spinlocks


Spinlocks
            A spinlock is a binary lock which the currently running program waits to become available
            before continuing the code execution flow. In the SmartDSP OS kernel, spinlocks protect
            the critical data or code among multiple cores. In addition, spinlocks can be used to
            synchronize the tasks executing on multiple cores. The spinlock uses atomic test-and-set
            operations (bmtset.w) for synchronization.
            In the SmartDSP OS kernel, a spinlock either:
              • protects the critical sections from access by other cores and Interrupt Service
                Routines (ISR) running on the same core, or
              • protects the critical section from access by other cores, but not from access by ISRs
                running on the same core.

            NOTE       bmtset.w is StarCore specific. Refer to SC3850 DSP Core Reference
                       Manual for more information about bmtset.w.

            The data is guarded locally on the core among tasks by enabling/disabling interrupts or by
            using osHwiSwiftDisable()/osHwiSwiftEnable() functions. Spinlocks should be used only
            when data is shared between cores.
            A spinlock in the SmartDSP OS kernel is 32 bits in memory, non-cacheable, and in
            memory which supports atomic operations, such as, M2 in MSC814x architecture and M3
            in MSC815x architecture.

            NOTE       Do not use the same spinlock on the same core in different priorities (HWI,
                       SWI, and/or tasks) without closing interrupts. A deadlock may occur.

            The following functions are used for acquiring spinlocks:
              • osSpinLockGet()— Acquires the spinlock. This is a blocking operation. Use
                this function with caution because of the possibility of deadlock.
              • osSpinLockIrqGet()— Disables interrupts and then acquires the spinlock.
                This is a blocking operation.
              • osSpinLockTryGet()— Tries to acquire the given spinlock. Returns whether or
                not the spinlock is acquired. This is a non-blocking operation.
            The following functions are used for releasing spinlocks:
              • osSpinLockRelease()— Releases the spinlock.
              • osSpinLockIrqRelease()— Releases the spinlock and then enables
                interrupts.




42                                                                       SmartDSP OS User Guide
Kernel Components
                                                                                    Memory Manager


           NOTE       The osSpinLockGet() and osSpinLockRelease() calls do not
                      disable interrupts, which can lead to deadlocks if an ISR tries to access the
                      critical section. Also, performance degradation can occur if one core gets the
                      spinlock and jumps to an ISR from within the critical section, leaving the other
                      cores waiting for the spinlock while the ISR is being served.

           To use a fake spinlock, define its address as OS_GUARD_DISABLE.
           OS_GUARD_DISABLE is a SmartDSP OS defined macro that when assigned to the
           spinlock, indicates that no action will take place on the spinlock and the core will not
           execute any syncio (blocking) instructions. The following source code shows how to use
           the OS_GUARD_DISABLE macro:
           uint32_t dummy_spinlock_addr = OS_GUARD_DISABLE; /* Won't
           take spinlock. Won't execute syncio */
           osSpinLockGet((volatile uint32_t *)dummy_spinlock_addr);


Memory Manager
           The memory manager component of the SmartDSP OS kernel module handles memory
           allocation and buffer management. The memory manager allocates memory blocks
           dynamically and frees them when they are no longer in use. The SmartDSP OS memory
           manager enables efficient allocation, retrieval, and release of memory blocks of known
           size and alignment without memory fragmentation.
           Memory management in SmartDSP OS is split into two stages, initialization and runtime.
           All initialization functions can be called at runtime and all runtime functions can be called
           at initialization.
           The SmartDSP OS default linker file provides a symmetrical view into the memory of
           each core, which:
             • allows easier transition from single to multicore.
             • allows easier reassignment of tasks from one core to another. For example, if a core
               starts and runs tasks A, B, and C and finds that it does not have the necessary
               bandwidth to create task D, the other core can create the task D and run it. However,
               it is not possible for one core to run a task created by another core.
             • allows easier debugging of memory-related bugs.
             • comes at the cost of aligning all cores to the core with the heaviest requirements.
           The SmartDSP OS partitions each shared physical memory into two main fragments:
             • Local, which is further fragmented based on the number of cores (Figure 2.4)
             • Shared (Figure 2.5 and Figure 2.6)



SmartDSP OS User Guide                                                                               43
Kernel Components
Memory Manager

Figure 2.4 Local Memory




           Figure 2.4, Figure 2.5, and Figure 2.6 shows the MSC814x default memory map.

Figure 2.5 Shared M3 Memory




44                                                                 SmartDSP OS User Guide
Kernel Components
                                                                                    Memory Manager

Figure 2.6 Shared DDR Memory




           Memory Allocation
           The memory manager supports the allocation of memory from different memory sections
           using the osMalloc() function. Note that the SmartDSP OS does not support an equivalent
           osFree() function and therefore allocated memory is never really released.
           In order to see how much memory is being consumed, you should modify the value of the
           flag OS_PRINT_MALLOC_STATISTICS in includecommonos_mem.h and recompile.
           This will cause each call to osMalloc() to produce on to the output console:
           "Core <core_num>. File: <file_name>. Line: <line_num>. osMalloc(<size>,
           <heap_name>)n"
           You can redirect the output to a file using os_malloc_file_handle = fopen(w,
           <user_file_name>);
           osMalloc() can be called at any time to allocate a slab on continuous (virtual) memory
           from a predefined heap.
           osMalloc() heaps are either shared or private, which are described as:
             • Shared heaps are described as an array, g_mem_heap_shared[], in the
               mscxxxx_shared_mem.c file
             • Private heaps are described as an array, g_mem_heap_local[], in the
               mscxxxx_init.c file
           A heap (os_mem_heap_t) is defined as having three distinctive characteristics:
             • Base address
             • Size



SmartDSP OS User Guide                                                                              45
Kernel Components
Memory Manager

               • Type (os_mem_type)
            Listing 2.6 shows an example of a heap.structure.

Listing 2.6 Structure of a heap

typedef struct
{
volatile uint32_t* mem_start;
volatile uint32_t* mem_size;
volatile uint32_t* mem_type;
} os_mem_heap_t;

            A SmartDSP OS application can add heaps into the arrays that can be allocated at compile
            time. Each heap has a distinctive enumeration. The SmartDSP OS defined heaps are
            enumerated in os_mem_type. The SmartDSP heap enumeration is split into the following
            three fields, each having a bit mask:
               • The valid field verifies the validity of a heap
               • The flags field specifies the characteristics (for example, shared, or cacheable) of the
                 heap
               • The memory type field specifies the type of memory (for example, M1, M2, M3,
                 DDR) in which the heap resides
            All heaps provided by SmartDSP will have OS_SMARTDSP_HEAP as one of the flags
            defined in their enumeration. This flag signifies that the heap is defined by the SmartDSP
            OS. The following source code snippet shows an example of a heap enumeration:
            OS_MEM_DDR0_LOCAL = (OS_VALID_NUM | OS_SMARTDSP_HEAP |
            OS_MEM_CACHEABLE_TYPE | OS_MEM_DDR0_TYPE),
            All other flags are assumed to be valid in any user-defined heap identifier.
            The main header file for memory management is os_mem.h. The memory types, flags, and
            validity checks are defined in os_mem.h as shown in Listing 2.7:

Listing 2.7 Memory type, flag, valid defined in os_mem.h

// MASK to extract memory type
#define OS_VALID_NUM_MASK                                                      0xFFF00000

/**< SmartDSP validity check number is encoded here */
#define OS_MEM_FLAGS_MASK                            0x000FF000

/**< Memory flags should be encoded in these bits */
#define OS_MEM_TYPE_MASK                             0x0000001F

/**< Memory type should be encoded in these bits */


46                                                                         SmartDSP OS User Guide
Kernel Components
                                                                                 Memory Manager

#define OS_VALID_NUM                                                        0xEC900000

/**< Used by SmartDSP code to ensure that this is a valid heap */

// Memory flags

#define OS_SMARTDSP_HEAP       0x00080000                     /**< Bit signifying that
the heap is defined by SmartDSP */
#define OS_MEM_CACHEABLE_TYPE 0x00040000                      /**< Bit signifying that
the heap is cacheable */
#define OS_MEM_SHARED_TYPE     0x00020000                     /**< Bit signifying that
the heap is shared */

// Memory types
#define OS_MEM_M1_TYPE         0x00000001                    /**< Heap in M1 memory */
#define OS_MEM_M2_TYPE         0x00000002                    /**< Heap in M2 memory */
#define OS_MEM_M3_TYPE         0x00000003                    /**< Heap in M3 memory */
#define OS_MEM_DDR0_TYPE       0x00000004                   /**< Heap in DDR0 memory */
#define OS_MEM_DDR1_TYPE       0x00000005                   /**< Heap in DDR1 memory */
#define OS_MEM_QE_PRAM_TYPE   0x00000006                    /**< Heap in QE PRAM memory
*/
#define OS_MEM_MAPLE_PRAM_TYPE 0x00000007                     /**< Heap in MAPLE PRAM
memory */


           NOTE       To prevent a user-defined heap identifier from clashing with a SmartDSP
                      identifier; do not define the OS_SMARTDSP_HEAP flag as part of the heap
                      identifier.



           Buffer Management
           The SmartDSP OS memory manager manages a pool of buffers, which can either be
           allocated statically during compilation or dynamically using osMalloc().The size of the
           memory manager is dependant on the number of buffers in the managed buffer pool. An
           application should use the MEM_PART_SIZE(<num buffers>) macro to define the
           memory size to allocate for the memory manager. The number of buffers to be managed
           by the memory manager is passed as an argument to the macro. An application can also
           use the MEM_PART_DATA_SIZE(<num buffers>,<buffer size>,<alignment>) macro
           for setting aside the buffer pool.
           For example, to manage 100 buffers that are dynamically allocated each having a size of
           73 bytes, with an alignment of 8 bytes, your application may call osMalloc() function as:
           osMalloc(MEM_PART_DATA_SIZE(100, 73, ALIGNED_8_BYTES),
           OS_MEM_LOCAL)



SmartDSP OS User Guide                                                                            47
Kernel Components
Memory Manager

            to allocate the buffer pool. Also, the macro MEM_PART_SIZE will take 100 as the
            argument while creating memory manager. Memory managers can manage shared as well
            as private buffer pools. Listing 2.8 displays the source code that an application uses for
            buffer management. The source code uses the function, osMemPartCreate(), which
            initializes a memory structure for aligned and fixed-size blocks.

Listing 2.8 Initializing memory structure for aligned and fixed-size blocks

os_mem_part_t * osMemPartCreate(uint32_t                             block_size,
                                uint32_t                             num_of_blocks,
                                uint8_t                              *data_address,
                                uint32_t                             alignment,
                                uint16_t                             buffer_offset,
                                os_mem_part_t                        *mem_part
 #if (OS_MULTICORE == 1)
                                 ,bool shared
 #endif
                          );

            The osMemPartCreate() function contains the following parameters:
               • block_size — Specifies the size of the allocatable block.
               • num_of_blocks — Specifies the maximum number of allocatable blocks.
               • data_address — Specifies the address of the contiguous block of buffers to
                 manage. The user application may use the MEM_PART_DATA_SIZE() macro to
                 set aside this memory.
               • alignment — Specifies how the blocks are aligned (in bytes).
               • buffer_offset — Specifies an offset in the buffer to be reserved for Low Level
                 Driver (LLD) or application use.
               • mem_part — Specifies the address of the memory manager space to initialize. The
                 user application may use the MEM_PART_SIZE() macro to set aside this memory.
               • shared — Specifies a flag that indicates whether this memory partition is shared
                 among cores or not. It receives a value of TRUE or FALSE.
            Listing 2.9 shows an example of how to allocate memory statically and then call the
            osMemPartCreate() function to manage the memory.

Listing 2.9 Allocating memory statically

os_mem_part_t *jobs_pool;
uint8_t       jobs_space[MEM_PART_DATA_SIZE(NUM_JOBS_PER_CORE,
sizeof(app_type_job), ALIGNED_4_BYTES)];
uint8_t       jobs_mem_manager[MEM_PART_SIZE(NUM_JOBS_PER_CORE)];
jobs_pool=


48                                                                       SmartDSP OS User Guide
Kernel Components
                                                                                  Memory Manager

osMemPartCreate(ALIGN_SIZE(sizeof(app_type_job),ALIGNED_4_BYTES),
                           NUM_JOBS_PER_CORE,
                           jobs_space,
                           ALIGNED_4_BYTES,
                           OFFSET_0_BYTES,
                          (os_mem_part_t *)&jobs_mem_manager,
                           FALSE);

           In the above source code example, jobs_pool is the memory manager that manages the
           buffer pool.
           jobs_space is the actual buffer structure that is to be managed. It stores the number of
           bytes that are to be managed by the memory manager. It can be initialized using the
           MEM_PART_DATA_SIZE macro as an argument, which contains the following three
           arguments:
             • Number of buffers — (NUM_JOBS_PER_CORE)
             • Size of buffers — (sizeof(app_type_job))
             • Alignment of buffers — ALIGNED_4_BYTES
           jobs_mem_manager manages job space itself using jobs_pool. It is a private partition and
           not shared. It can be initialized using the MEM_PART_SIZE(NUM_JOBS_PER_CORE)
           macro, which contains the NUM_JOBS_PER_CORE argument.
           Based on this memory allocation, the osMemPartCreate() function is called where:
             • ALIGN_SIZE(sizeof(app_type_job), ALIGNED_4_BYTES) —
               Indicates that memory manager manages the memory blocks where the size of each
               block is the size of the structure aligned. The aligned structure is defined in
               os_mem.h. The alignment of the structure is four bytes.
             • NUM_JOBS_PER_CORE — Indicates the number of blocks that the memory
               manager will manage.
             • jobs_space — Indicates the address of the blocks.
             • jobs_mem_manager — Indicates the memory manager containing the number of
               jobs per core to be managed.
             • FALSE — Indicates that the memory partition is not shared.
           The osMemPartCreate() function returns a pointer to the initialized memory managing
           structure (os_mem_part_t).
           Use these functions to retrieve buffers:
             • void * osMemBlockGet(os_mem_part_t *mem_part) — Retrieves a
               block form the memory manager.
             • void * osMemBlockUnsafeGet(os_mem_part_t *mem_part) —
               Retrieves a block form the memory manager (unsafe version). Use this function



SmartDSP OS User Guide                                                                                49
Kernel Components
Memory Management Unit (MMU)

                when you are sure that the memory manager cannot be accessed from any other
                source.
             • void * osMemBlockSyncGet(os_mem_part_t *mem_part) —
               Retrieves a block from the memory manager (multicore safe version).
           Use these functions to free buffers:
             • void osMemBlockFree(os_mem_part_t *mem_part, void *addr)
               — Releases a block back to the memory manager.
             • void osMemBlockUnsafeFree(os_mem_part_t *mem_part, void
               *addr) — Releases a block back to the memory manager (unsafe version). Use this
               function when you are sure that the memory manager cannot be accessed from any
               other source.
             • void osMemBlockSyncFree(os_mem_part_t *mem_part, void
               *addr) — Releases a block back to the memory manager (multicore safe version).


Memory Management Unit (MMU)
           An MMU is a hardware component that is used to extend memory addressing capabilities
           and control access to Random Access Memory (RAM) and entire SoC. The MMU
           translates the logical addresses into physical memory addresses. An MMU is used to map
           and protect memory segments on each core.
           The SmartDSP OS for MSC814x and later platforms provides MMU support, which:
             • supplies hardware memory protection for instruction and data accesses.
             • supports the bridging of two privilege levels (user and supervisor).
             • implements high-speed address translations from virtual to physical address.
             • provides cache and bus control for advanced memory management.
             • supports software coherency with cache sweep operations that invalidate, flush, and
               synchronize.
           For address translation, there is a software model in which the source code is written in
           virtual addresses that are translated to physical addresses before issuing them to memory.
           The SmartDSP OS distinguishes between program and data attributes of the MMU. The
           SmartDSP OS extensively uses the MMU for building the same virtual memory map that
           includes both local and shared memory for each core. Shared memory is accessible by all
           the cores and local regions are accessible by only one core. The MMU makes it easier to
           port single core applications by creating an identical single core alike virtual map. In this
           way, every core owns its local memory with explicitly defined regions for shared memory.




50                                                                       SmartDSP OS User Guide
Kernel Components
                                                              Memory Management Unit (MMU)


           MMU Features
           As part of the DSP Subsystem, an MMU:
             • provides memory region support as follows:
                – Provides read allowed/not allowed for both supervisor and user levels in the
                  program memory region
                – Provides read/write allowed/not allowed for both supervisor and user levels in the
                  data memory region
             • defines address translation for each data/program memory region so that a virtual
               memory region can be allocated to a valid physical memory space.
             • stores the program task ID and data task ID for multi-task mechanism.
             • handles access error detection with support for non-mapped memory access and
               misaligned memory access.
             • presents two abstractions, Segment and Context, in SmartDSP.
             • defines cache policy on each segment.


           MMU Segment
           An MMU segment defines a memory region and its attributes, protection, and address
           translation. Each MMU segment is either a program or data but not both. Segment
           programming is predefined in the Linker Command File (LCF), during runtime, or a
           combination of both. Refer to the relevant DSP subsystem Reference Manual for MMU
           alignment restrictions.
           An MMU segment includes:
             • memory translation
             • permissions
             • cache properties
             • memory properties

           NOTE      The SmartDSP OS collectively refers to data and program segments as system
                     segments.



           MMU Segment Abstraction
           MMU segment abstraction includes cache attributes and provides a single translation from
           virtual to physical addresses (see Figure 2.7).




SmartDSP OS User Guide                                                                             51
Kernel Components
Memory Management Unit (MMU)

Figure 2.7 MMU Segment




           Both system and user segments are available in the SmartDSP OS. System segments are
           included in the SmartDSP OS application contexts. User segments are only included
           through a specific context. Multiple contexts can include the same user segment.


           MMU Segment Creation
           In the initialization phase, the SmartDSP OS creates MMU segments according to the
           executable, using an environment-specific format. In CodeWarrior IDE, for example, an
           application uses the Linker Command File (LCF) for segment definition and attribute and
           ID associations. In this case, the SmartDSP OS enables all system segments and adds them
           to the system context. The SmartDSP OS adds user segments to the user contexts
           according to the context definition.
           An application creates a MMU segment explicitly using the API functions,
           osMmuProgSegmentCreate() and osMmuDataSegmentCreate(). These functions create
           MMU segments according to the given parameters. After creating the segment, the
           segment can be added to any context using the osMmuDataContextSegmentsAdd() or
           osMmuProgContextSegmentsAdd() functions. In such cases, the segment is active when
           the context is active. It is also possible to enable the segment using the
           osMmuDataContextActivate() function.

           NOTE      If a MMU segment is added to the current context, the SmartDSP OS activates
                     it upon the next activation of the context.

           An example of the activation of an MMU segment is shown in Listing 2.10.

Listing 2.10 Activating a MMU segment

status = osMmuDataSegmentFind(&data_segment);
if (status != OS_SUCCESS) OS_ASSERT;

status = osMmuDataSegmentCreate(data_segment,(void*)VIRT_BASE1,
(void*)PHYS_BASE1,
SEGM_SIZE,
MMU_DATA_DEF_SYSTEM,


52                                                                    SmartDSP OS User Guide
Kernel Components
                                                                Memory Management Unit (MMU)

NULL);
if (status != OS_SUCCESS) OS_ASSERT;

status = osMmuDataSegmentEnable(data_segment, TRUE);
if (status != OS_SUCCESS) OS_ASSERT;

           In the above example, the application activates a segment rather than adding it to a given
           context. The segment is active only until the next context switch.


           MMU Context
           A SmartDSP OS MMU context is a group of segments that can be associated with a task.
           An MMU context defines a subset of software context.
           An MMU context defines a set of active segments as well as an ID. This ID is the PID/
           DID of all tasks belonging to the context. An MMU context is shown in Figure 2.8.

Figure 2.8 MMU Context




           There are two types of contexts. A program context is a set containing a unique program
           ID and a subset of defined program segment descriptors. A data context is a set with a
           unique data ID and a subset of defined data segment descriptors.
           Each task belongs to a single data context and program context. By default, tasks belong to
           system contexts but for segment mapping, they maintain their own unique PID/DID. A
           task belonging to a context, which has been associated to the task during runtime, has data
           ID at that context and the set of segments enabled in that context. Tasks do not need to
           belong to the same context for data and program. Each task is created using the MMU
           segment of the system context. The system PID/DID is 1.


           MMU Context Abstraction
           The SmartDSP OS preserves data and program contexts on each HWI and SWI. System
           context is enabled on each task and HWI/SWI interrupt. The system contexts begin by
           including segments for which MMU_PROG_DEF_SYSTEM or
           MMU_DATA_DEF_SYSTEM was set in the segment attributes in LCF.


SmartDSP OS User Guide                                                                             53
Kernel Components
Memory Management Unit (MMU)

           User context normally includes all system context segments because they must be enabled
           continuously. However, in some cases, system context segments are removed from the
           user context. System context usually only includes system segments but it can also include
           user segments.

           NOTE       Changes to the system contexts are reflected in all contexts.



           MMU Context Creation
           The SmartDSP OS creates all MMU contexts using information from LCF. An application
           creates a MMU context explicitly by using osMmuDataContextFind() and
           osMmuProgContextFind(). These functions send a pointer to the first available context
           and set a supplied ID to the context. An application modifies the MMU context by adding
           new segments using osMmuProgContextSegmentsAdd() or
           osMmuDataContextSegmentsAdd().
           The osMmuProgSystemContextSegmentAdd() function adds a given segment to the
           system program context and this reflects in all program contexts. You can add a segment
           to the system context only by using the osMmuDataContextFind() function with the
           parameter, OS_MMU_SYSTEM_CONTEXT. You can associate an MMU context with a
           SWI by calling the osSwiMmuDataContextSet() function. This allows SmartDSP OS to
           activate the system context when a SWI starts and then replace the system context with the
           context you specify. An application enables the context by calling the
           osMmuDataContextActivate() function, which has the same effect as a task switch. An
           MMU context creation is shown in Figure 2.9.

Figure 2.9 MMU Context Creation




54                                                                      SmartDSP OS User Guide
Kernel Components
                                                               Memory Management Unit (MMU)


           MMU Configuration
           The main header file of the SmartDSP OS MMU is includecommonos_mmu.h. The
           number of data and program contexts have default values which can be overridden in
           os_config.h in the following definitions:
             • #define MMU_DATA_CONTEXT_NUM                  <num>
             • #define MMU_PROG_CONTEXT_NUM                  <num>
           An array of data and program contexts will be allocated from the OS_MEM_LOCAL
           heap. The user application will therefore face the penalty in terms of memory footprints
           for defining an improper number of contexts or for defining too many contexts that
           override the default value. Tasks and contexts share the reserved number of IDs that are
           defined in the MMU (platform specific), which is
           1+num_tasks+num_contexts<=max_ID.
           MMU segments (both data and program) that are not defined in the LCF can be added
           during initialization or runtime using the following functions:
             • osMmuDataSegmentFind()
             • osMmuDataSegmentCreate()
             • osMmuDataSegmentEnable()
             • osMmuProgSegmentFind()
             • osMmuProgSegmentCreate()
             • osMmuProgSegmentEnable()
           Once an MMU segment is created, it can be added to a MMU context using the following
           functions:
             • osMmuDataContextSegmentsAdd()
             • osMmuProgContextSegmentsAdd()
             • osMmuDataSystemContextSegmentAdd()
             • osMmuProgSystemContextSegmentAdd()
           MMU Segments can also be removed from MMU contexts using the following functions:
             • osMmuDataContextSegmentRemove()
             • osMmuProgContextSegmentRemove()
             • osMmuDataSystemContextSegmentRemove()
             • osMmuProgSystemContextSegmentRemove()
           To perform address translation, an application can call the following functions:
             • osMmuProgVirtToPhys()
             • osMmuDataVirtToPhys()



SmartDSP OS User Guide                                                                            55
Kernel Components
Memory Management Unit (MMU)

            To perform address validation, an application can call the following functions:
              • osMmuProgVirtProbe()
              • osMmuDataVirtProbe()


            MMU Exceptions
            MMU exceptions are non-maskable and precise. The SmartDSP OS has default handlers
            for program and data MMU exceptions, which can perform the following tasks:
              • Detect the context from which the error occurred
              • Detect the root cause of the error and clear the interrupt in the MMU
              • Call a user-defined debug hook if enabled
              • Stop the core
            An application can override these exceptions by calling osHwiDelete() followed by
            osHwiCreate() for OS_INT_DMMUAE (data MMU) and/or OS_INT_IMMUAE
            (instruction MMU). Use the function, osMmuDataErrorDetect() or
            osMmuProgErrorDetect() to clear the interrupt and return one of the root causes of the
            exception, as shown:
              • status = osMmuDataErrorDetect(struct os_mmu_error *)
              • status = osMmuProgErrorDetect(struct os_mmu_error *)
            An example of returning the cause of an MMU error is shown in Listing 2.11.

Listing 2.11 Returning the cause of MMU error

struct os_mmu_error
{
   uint32_t error_address;                   //violation address
  uint32_t error_pc;                       //program counter that caused exception
   uint32_t rw_access;                     //read is 0, write is 1
   uint32_t privilege_level;             //user is 0, supervisor is 1
   uint32_t access_width;                //Access Violation Width
};

            There are two non-contradicting procedures to debug a MMU error.
            First procedure:
            1. Look at the root cause of the error using status of the os_mmu_error structure.
            2. View memory as program at the err.error_pc to look at the program counter
               where error happened.
            3. See what you are doing.
            4. Compare with what you meant to have been doing.


56                                                                       SmartDSP OS User Guide
Kernel Components
                                                                                               Caches

           5. See where the error originated.
           Second procedure:
           1. Step out of the handler.
           2. Step through the interrupt dispatcher (_osHwiPreciseDispatcher).
           3. Step back into the code.
           4. Look at the stack and see where the error originated.


Caches
           A cache is a high-speed memory area where the information is stored temporarily for fast
           access. The information retrieved from main memory is copied to the cache. The CPU
           fetches the information from the cache instead of main memory. This reduces the access
           time and enhances memory performance.
           The SmartDSP OS supports different types and hierarchies of cache memories. Level 1 or
           L1 cache is an internal cache that is generally very small and private. Level 2 or L2 cache
           is the secondary cache, also referred to as external cache. It is larger and slower, compared
           to L1 cache.
           The SmartDSP OS kernel has extensive cache functionality for the MSC814x and
           MSC815x platforms. The SoC caches supported by StarCore processors are shown in
           Table 2.4.

Table 2.4 StarCore SoC Caches

            Processor                                   Cache

            MSC8101                                     No cache

            MSC812x                                     private L1-I$

            MSC814x                                     private L1-I$/D$, shared L2-I$

            MSC815x                                     private L1-I$/D$, private unified L2



           NOTE       For MSC812x, the SmartDSP OS only enables or disables the cache.



           Cache Sweep Commands
           Each MMU segment has specific cache characteristics defined during segment creation or
           in the LCF. An application utilizes cache sweep commands, which are a mechanism to


SmartDSP OS User Guide                                                                               57
Kernel Components
Caches

         support platform cache coherency. This mechanism enables data sweeping (such as
         invalidate, flush, and synchronize) of a specific range of addresses that are programmed in
         the cache registers.
         The SmartDSP OS supports two types of sweep commands:
           • Synchronous (or blocking) — The sweep command is accomplished after return. The
             synchronous function, osCacheDataSweep() performs the requested action on
             data cache and polls until the operation is finished.
           • Asynchronous (or non-blocking) — The sweep operation can be in process after
             return. The asynchronous function, osCacheDataSweepAsync() performs the
             requested action on data cache and returns.
         Both the synchronous and asynchronous functions initially check whether previous
         commands have been completed or not. An application can check the status of the sweep
         operation by using the osCacheDataInProgressSweep() function.


         Configuration of Caches in SmartDSP OS
         The main header file of the SmartDSP OS caches is includecommonos_cache.h.
         The SmartDSP OS distinguishes between the various caches in the system and provides an
         API for each supported type. At initialization, caches are configured based on the
         following definitions in the os_config.h file:
           • #define DCACHE_ENABLE                ON
           • #define ICACHE_ENABLE                OFF
           • #define L2CACHE_ENABLE               ON     //MSC815x only
           • #define OS_L2_CACHE_SIZE ((uint32_t)&_L2_cache_size)
             // in MSC815x only for specifying how much shared M2 and
             L2 be used as core M2 memory or as L2 cache
         There are two types of hardware-supported cache operations: Global and By Address. The
         function, osCacheL2ProgSweepGlobal() sweeps the L2 program globally on the entire
         cache. The function, osCacheProgSweep(), performs a sweep operation by address on
         program cache.
         The L1 caches in MSC814x and MSC815x platforms work with virtual addresses. L2
         caches do not work with virtual addresses. Non-global L1 cache operations require a task
         ID. On shared segments, an application should use MMU_SHARED_PID.
         Non-global cache operations must specify addresses with the granularity of cache lines. A
         cache line contains multiple Valid Bit Resolution (VBR) chunks of memory.
         Although cache operations for hardware can operate on VBR-by-VBR basis, the
         minimum granularity for L1 cache operations is the cache line. This means that cache
         operations are performed on all VBR in the cache line. Therefore, the SmartDSP OS
         enforces the granularity of cache lines while calling the cache sweep operation.


58                                                                    SmartDSP OS User Guide
Kernel Components
                                                                                               Queues

            The SmartDSP OS provides the ARCH_CACHE_LINE_SIZE macro for allowing easy
            alignment to the L1 cache line size. The following macros are available for aligning cache
            operations to line size:
              • #define CACHE_OP_LOW_ADDR (VIRT_BASE, GRANULARITY)
              • #define CACHE_OP_HIGH_ADDR (VIRT_BASE, SIZE,
                GRANULARITY)
            The alignment of cache operations to cache line size is shown in Listing 2.12.

Listing 2.12 Alignment of cache operations to the cache line size

long read_from_maple(void* addr, void* data, uint32_t size, uint32_t
dev_id)
{
   os_status status;
   uint32_t   cache_addr_lo,cache_addr_hi;

    cache_addr_lo=CACHE_OP_LOW_ADDR(data, ARCH_CACHE_LINE_SIZE);
    cache_addr_hi=CACHE_OP_HIGH_ADDR(data, size,ARCH_CACHE_LINE_SIZE);

    osCacheDataSweep((void*)cache_addr_lo,
                     (void*)cache_addr_hi,
                      MMU_SHARED_PID,
                      CACHE_FLUSH);

    return (long)size;
}




Queues
            A queue is a linear data structure which contains a collection of entities. The entities are
            added at the rear end and removed from the front end. A SmartDSP OS queue implements
            a First in First Out (FIFO) algorithm. Queues in SmartDSP OS are used as a basic
            component in various abstraction layers and utilities. The queues are private per core and
            they queue data that is four bytes in size (uint32_t). A queue can be either specific to a
            core, or can be shared by all cores. All queues are protected from access by the same core.
            There is a special version of queues called multiple queues, which queue different sizes of
            data. The size is determined while creating the queue. Currently, the queue component
            supports the queuing of 32 bit values only. In the configuration file, an application can
            define the maximum number of both regular queues and shared queues allowed by the
            system.




SmartDSP OS User Guide                                                                               59
Kernel Components
Queues

            Queues send one or more messages to a task. A task can use a queue to post messages to
            software or hardware interrupts. A task or interrupt handler can place a message in the
            form of a pointer in the queue as well as receive messages from the queue.
            The SmartDSP OS provides two kinds of queue, shared and private. Shared queues use
            spinlocks and are allocated using OS_MEM_SHARED. Private queues are allocated using
            OS_MEM_LOCAL and override the spinlock mechanism using OS_GUARD_DISABLE.
            Queue runtime API may be either safe or unsafe, which are equally legal for both shared
            and private queues. The functions in the safe queue runtime API are protected with
            osSpinLockIrqXxx(). No protection is provided in the unsafe queue runtime API.
            An application defines the number of queues in the os_config.h file as:
            #define OS_TOTAL_NUM_OF_QUEUES                   48
            #define OS_TOTAL_NUM_OF_SHARED_QUEUES                     0
            Perform the following steps to create a queue. You should perform these steps in your
            application's initialization source code because these steps involve memory allocations.
            1. Get a handle to a queue by calling osQueueFind(), specifying whether you need to
               find a shared queue or a regular queue.
            2. Call osQueueCreate() after you find a valid queue handle. This function
               initializes the queue with the required size.
            3. Use osQueueEnqueue() to start inserting items into the queue, and
               osQueueDequeue() to remove items.
            The functions available in the queue module of the SmartDSP OS are listed in Table 2.5.

Table 2.5 Functions Available for Queues

             Flow State                         Name                        Description

             Kernel bring up (the user          osQueueInitialize           Initializes the OS
             application does not call these    ()                          queues.
             functions specifically. Instead,
             osInitialize() calls these
             functions based on the
             parameters from os_config.h
             and configurations from
             msc81xx_config.c)

             Application bring up               osQueueFind()               Finds the first available
                                                                            queue number.

                                                osQueueCreate() or          Prepares a queue for
                                                osQueueCreateMult           operation.
                                                iple()




60                                                                        SmartDSP OS User Guide
Kernel Components
                                                                                  Queues

Table 2.5 Functions Available for Queues (continued)

             Flow State                   Name                  Description

             Application runtime          osQueueEnqueue() or   Inserts a value into a
                                          osQueueEnqueueMul     queue.
                                          tiple()

                                          osQueueUnsafeEnqu     Inserts a value to a
                                          eue() or              queue (unsafe version).
                                          osQueueUnsafeEnqu     Use this function when a
                                          eueMultiple()         queue object cannot be
                                                                accessed from any
                                                                other source.

                                          osQueueHeadEnqueu     Inserts a value into the
                                          e()                   front of a queue.

                                          osQueueUnsafeHead     Inserts a value into the
                                          Enqueue()             front of a queue (unsafe
                                                                version). Use this
                                                                function when a queue
                                                                object cannot be
                                                                accessed from any
                                                                other source.

                                          osQueueDequeue() or   Removes the first value
                                          osQueueDequeueMul     from a queue.
                                          tiple()

                                          osQueueUnsafeDequ     Removes the first value
                                          eue() or              from a queue. Use this
                                          osQueueUnsafeDequ     function when a queue
                                          eueMultiple()         object cannot be
                                                                accessed from any
                                                                other source.

                                          osQueueTailDequeu     Removes the last value
                                          e()                   from a queue.

                                          osQueueUnsafeTail     Removes the last value
                                          Dequeue()             from a queue. Use this
                                                                function when a queue
                                                                object cannot be
                                                                accessed from any
                                                                other source.




SmartDSP OS User Guide                                                                     61
Kernel Components
Intercore Messaging

Table 2.5 Functions Available for Queues (continued)

             Flow State                         Name                       Description

                                                osQueueStatus()            Queries the status of a
                                                                           queue, such as
                                                                           OS_QUEUE_EMPTY or
                                                                           OS_QUEUE_FULL.

                                                osQueueUnsafeStat          Queries the status of a
                                                us()                       queue, such as
                                                                           OS_QUEUE_EMPTY or
                                                                           OS_QUEUE_FULL. Use
                                                                           this function when a
                                                                           queue object cannot be
                                                                           accessed from any
                                                                           other source.

                                                osQueueReset() or          Empties the given
                                                osQueueResetUnsaf          queue
                                                e()

                                                osQueuePeek()              Queries the first value in
                                                                           the queue without
                                                                           removing it.

             Application tear down              osQueueDelete()            Deletes the given queue
                                                                           from the system.


            All queues, including unshared queues, are protected from access by the same core. In a
            multicore system, an application can request the queue to be a shared queue. The shared
            queue object resides in the shared memory and is protected from access by other cores.


Intercore Messaging
            In a multicore environment, intercore messaging allows applications running on different
            cores to communicate with each other. The intercore messaging component of the
            SmartDSP OS module allows communication between applications through messages by
            associating interrupts with handlers written in C or assembly language.
            Intercore messages in the SmartDSP OS are point-to-point. An application can post an
            intercore message at any time. Reception of intercore messaging is possible only after
            creating the message or listening to the message. Intercore messaging in the SmartDSP OS
            may be either synchronous or asynchronous.
             Synchronous intercore messaging uses the following process:



62                                                                     SmartDSP OS User Guide
Kernel Components
                                                                                  Intercore Messaging

           1. The sending core takes a mailbox spinlock.
           2. The sending core writes data to a mailbox.
           3. The sending core interrupts a recipient.
           4. The recipient is interrupted. Mailbox number is returned as an interrupt handler
              argument (os_hwi_arg).
           5. The recipient reads mailbox data.
           6. The recipient frees the spinlock.
           Asynchronous intercore messaging uses the following process:
           1. Data is predefined during initialization and set as an interrupt handler argument
              (os_hwi_arg).
           2. The sending core interrupts the recipient.
           3. The recipient is interrupted.
           The VIRQ were used for intercore messaging in MSC812x and MSC814x. In MSC815x,
           the interrupt mesh between cores is used for intercore messaging. The kernel initializes the
           inter-core messaging module of the SmartDSP OS using the osMessageInitialize()
           function.


           Configuration of Intercore Messaging
           The main header file of the SmartDSP OS intercore messages is:
           includecommonos_message.h.
           Intercore messaging is only enabled where OS_MULTICORE is predefined as 1 (that is,
           not enabled in MSC8101). The maximum number of supported messages in the
           architecture is defined in smartdsp_os_device.h as:
           #define MSC814X_MAX_NUM_OF_MESSAGES                      4
           #define MSC815X_MAX_NUM_OF_MESSAGES                      2
           The number of intercore messages is defined by an application in os_config.h, as:
           #define OS_TOTAL_NUM_OF_INTERCORE_MESSAGES                         1

           NOTE       The number of messages should be interpreted as the number of point-to-point
                      messages; that is, multiplied by the number of cores.

           An application defines the maximum number of intercore messages allowed by the system
           in the configuration file. Intercore messaging mailboxes are allocated from the
           OS_SHARED_MEM heap during initialization. Because intercore messaging uses
           spinlocks, a requirement is placed on the physical memory in which this heap is linked.
           Refer to SmartDSP OS API Reference Manual for more information.
           Functions available for intercore messaging are listed in Table 2.6.


SmartDSP OS User Guide                                                                              63
Kernel Components
Intercore Messaging


Table 2.6 Functions Available for Intercore Messaging

             Flow State                         Name                  Description

             Kernel bring up (the user          osMessageInitiali     Initializes the multicore
             application does not call these    ze()                  synchronization
             functions specifically. Instead,                         module.
             osInitialize() calls these
             functions based on the
             parameters from os_config.h
             and configurations from
             msc81xx_config.c)

             Application bring up               osMessageFind()       Finds the first available
                                                                      inter-core message
                                                                      number.

                                                osMessageCreate()     Installs an intercore
                                                or                    message handler for the
                                                osMessageCreateAs     calling core to start the
                                                ync()                 communication. When a
                                                                      specific message
                                                                      arrives, this function
                                                                      enables the calling core
                                                                      to be notified. The
                                                                      calling core can then
                                                                      handle the message.




64                                                                  SmartDSP OS User Guide
Kernel Components
                                                                       Intercore Messaging

Table 2.6 Functions Available for Intercore Messaging (continued)

             Flow State                   Name                      Description

             Application runtime          osMessagePost() or        Posts the given
                                          osMessagePostIrq(         message number or ID
                                          ) or                      with the given data to
                                          osMessagePostAsyn         the destination core.
                                          c()                       This function performs
                                                                    the following tasks:
                                                                      • Posts a virtual
                                                                        interrupt to
                                                                        the
                                                                        destination
                                                                        core and
                                                                        associates a
                                                                        message with
                                                                        this interrupt
                                                                      • Gets a
                                                                        message ID
                                                                        and pass it to
                                                                        handler as
                                                                        parameter
                                                                    While the message is
                                                                    posted, no other core
                                                                    can post the same
                                                                    message number to the
                                                                    same core. As a result,
                                                                    the data is safe until the
                                                                    destination core fetches
                                                                    the message.

                                          osMessageGet()            Retrieves the data from
                                                                    a message (with the
                                                                    message ID) that was
                                                                    posted to the calling
                                                                    core.
                                                                    When your application
                                                                    receives a message,
                                                                    you must call
                                                                    osMessageGet() to
                                                                    dismiss the interrupt,
                                                                    even if you are not
                                                                    interested in the
                                                                    contents of the
                                                                    message.




SmartDSP OS User Guide                                                                           65
Kernel Components
Intercore Message Queues

Table 2.6 Functions Available for Intercore Messaging (continued)

             Flow State                         Name                        Description

             Application tear down              osMessageDelete()           Deletes an existing
                                                                            intercore message
                                                                            handler. The deleted
                                                                            message number
                                                                            cannot be used after it
                                                                            is deleted.



Intercore Message Queues
            The intercore message queue module of the SmartDSP OS is used for inter-process
            communication within the same process or intercore communication which is not
            necessarily point-to-point. The intercore message queue uses a queue for transferring the
            messages or content between processes.
            Intercore message queues in the SmartDSP OS are point-to-multipoint. Enqueuing and de-
            queuing from a message queue is possible only after creating it. In all architectures,
            message queues use VIRQ. As a result, the number of message queues is bound only by
            the number of other VIRQ users, such as intercore messaging (on MSC812x/MSC814x)
            and RIONET (on MSC814x/MSC815x), and the number of VIRQ in the SoC.
            The kernel initializes the intercore message queue module of the SmartDSP OS by using
            the osMessageQueueInitialize() function.


            Configuration of Intercore Message
            Queues in SmartDSP OS
            The main header file of the SmartDSP OS intercore message queue is
            includecommonos_message_queue.h. Intercore message queues are allocated from the
            OS_SHARED_MEM heap during initialization. Intercore messaging is only enabled
            where OS_MULTICORE is predefined to 1; therefore it cannot be enabled in the
            MSC8101 platform.
            The number of intercore message queues is defined by an application in os_config.h as:
            #define OS_TOTAL_NUM_OF_MESSAGE_QUEUES                      1
            Refer to SmartDSP OS API Reference Manual for more information.
            The functions available in the intercore message queue module of the SmartDSP OS are
            listed in Table 2.7.




66                                                                      SmartDSP OS User Guide
Kernel Components
                                                                      Intercore Message Queues


Table 2.7 Functions Available for Intercore Message Queues

             Flow State                    Name                         Description

             Application bring up          osMessageQueueCreat          Installs an intercore
                                           e()                          message handler for the
                                                                        calling core. Then, the
                                                                        calling core can handle the
                                                                        message.

             Application runtime           osMessageQueuePost(          Posts the given message
                                           )                            number with the given
                                                                        data to the destination
                                                                        core.

                                           osMessageQueueGet()          Retrieves the data from a
                                           or                           message that was posted
                                           osMessageQueueDispa          to the calling core.
                                           tcher()
                                                                        Note: User may call the
                                                                        function repetitively until
                                                                        the queue is empty:
                                                                        while(OS_ERR_Q_EMPT
                                                                        Y !=
                                                                        osMessageQueueGet()
                                                                        );

             Application tear down         Not supported



            Intercore Options
            The SmartDSP OS provides various intercore options to establish communication between
            cores in a multicore platform. An application can use any of the following options while
            using intercore messaging APIs (see Figure 2.10):
              • Standard AMP scheduler where each core handles it's own tasks
              • Data flow between core using intercore messages
              • Master-Slave or producer-consumer using message queues




SmartDSP OS User Guide                                                                                67
Kernel Components
Events

Figure 2.10 Intercore Options




Events
            An event is a kernel object that enables communication between tasks and the system.
            Tasks, except background task, can remain pending on events until an event is available or
            when a timeout occurs. An HWI, SWI, or another task can post the event to restart a
            blocked task. An event can also be referred as a function in the system that an HWI, SWI,
            or task can accept to check if it is available. Events enable signals to the blocking task to
            notify that the task should wake up and give some data to the event, if necessary. An event
            may include data; therefore, it is possible to post and receive a message from an event.
            Events are a ‘base class’ in the SmartDSP OS. There is no public header file for events and
            an application is not expected to call its functionality directly.
            Events cannot be shared among different cores. Events and their derivatives are private in
            each core. The following lists some of the scenarios of events:
              • Events have a list of pending tasks for the specific event.
              • If an event is available, the pending task is not blocked and there is no delay in its
                execution.
              • If a function in the system posts an event and a task is pending on that event then the
                posting function will get the pending task ID.


68                                                                         SmartDSP OS User Guide
Kernel Components
                                                                                               Events

              • If no task is pending on a posted event, it will return TASK_NULL_ID.
              • If an event is not available, the task gets blocked and a context switch occurs.
              • If a task is blocking the number of seconds it specified as timeout, it becomes ready
                and the pending function returns OS_ERR_EVENT_QUEUE_TIMEOUT or
                OS_ERR_EVENT_QUEUE_TIMEOUT.
            There are two types of events in the SmartDSP OS: semaphores and queues.


            Event Semaphores
            A semaphore event is used to synchronize a task with an HWI, SWI, or another task.
            Semaphore events can be posted multiple times or accepted an equal number of times. To
            use a semaphore event for synchronization purposes, set its value to 0. For example, a task
            initiates an (I/O) operation and then waits for a semaphore. When the I/O operation
            finishes, an SWI, HWI, or another task sets the semaphore and the task resumes.
            The initialization of event semaphores is handled by the events base class.
            An application defines the number of event semaphores in the os_config.h file, using this
            definition:
            #define OS_TOTAL_NUM_OF_EVENT_SEMAPHORES                       5
            A software or hardware interrupt handler that waits for a semaphore, must call the non-
            blocking command osEventSemaphoreAccept(), or it will fail. Background tasks cannot
            pend on a semaphore because such tasks must never block. The running task can pend on
            a semaphore with a possible timeout time measured in ticks. The running context (task or
            interrupt) can always post to a semaphore.
            To create and delete a semaphore, use the functions shown in Listing 2.13:

Listing 2.13 Functions for creating and deleting semaphore

status = osEventSemaphoreFind(&s);
OS_ASSERT_COND(status == OS_SUCCESS);

status = osEventSemaphoreCreate(s, 0);
OS_ASSERT_COND(status == OS_SUCCESS);

status = osEventSemaphoreDelete(s);
OS_ASSERT_COND(status == OS_SUCCESS);

            The following code snippet (Listing 2.14) shows an example of a task pointing to a
            semaphore, another task pending on it, and interrupt handler accepting it:




SmartDSP OS User Guide                                                                              69
Kernel Components
Events

Listing 2.14 Tasks pointing to and pending on a semaphore

status = osEventSemaphorePend(S, TIMEOUT);                                //Task1
OS_ASSERT_COND(status == OS_SUCCESS);

status = osEventSemaphorePost(S, &resumed_task);                         //Task 2
OS_ASSERT_COND(status == OS_SUCCESS);

status = osEventSemaphoreAccept(s);                                    //Interrupt Handler

            The functions available in the event semaphores module of the SmartDSP OS are listed in
            Table 2.8.

Table 2.8 Functions Available for Event Semaphores

             Flow State                    Name                           Description

             Kernel bring up                                              Already handled by the
                                                                          Events ‘base class’.

             Application bring up          osEventSemaphoreFind           Receives a handle to
                                           ()                             create a semaphore
                                                                          event.

                                           osEventSemaphoreCrea           Creates a semaphore
                                           te()                           event. Initializes a
                                                                          semaphore counter and
                                                                          an empty waiting list and
                                                                          places them in an event
                                                                          structure.

             Application runtime           osEventSemaphorePend           Pends on a counting
                                           ()                             semaphore if
                                                                          semaphore counter is
                                                                          zero; otherwise,
                                                                          decrements and
                                                                          continues.

                                           osEventSemaphoreAcce           Continues semaphore
                                           pt()                           without pending. Checks
                                                                          if semaphore counter is
                                                                          not zero, whereupon it
                                                                          decrements the counter.




70                                                                    SmartDSP OS User Guide
Kernel Components
                                                                                              Events

Table 2.8 Functions Available for Event Semaphores (continued)

             Flow State                      Name                           Description

                                             osEventSemaphorePost           Posts a counting
                                             ()                             semaphore. If tasks are
                                                                            pending on the
                                                                            semaphore, it schedules
                                                                            them; otherwise,
                                                                            increments the counter
                                                                            and continues.

                                             osEventSemaphoreRese           Removes all tasks
                                             t()                            pending on the event
                                                                            and schedule them if
                                                                            they are ready.

             Application tear down           osEventSemaphoreDele           Resets semaphore and
                                             te()                           deletes the semaphore.
                                                                            Releases the event
                                                                            structure used for the
                                                                            counting semaphore
                                                                            and resumes all tasks
                                                                            pending on it.



            Event Queues
            Event queues are used to store events, which are due to be processed. Event queues require
            both events and queues to be in the system. An application defines the number of event
            queues in the os_config.h file, as:
            #define OS_TOTAL_NUM_OF_EVENT_QUEUES                     3

            NOTE       The function for deleting an event queue is not supported, yet.

            A handler that receives a message must call the non-blocking command,
            osEventQueueAccept(), or it will fail. Background tasks cannot pend on a queue, because
            such tasks must never block.
            To find and create an event queue, use the functions in Listing 2.15:

Listing 2.15 Finding and creating an event queue

status = osEventQueueFind(&Q);
OS_ASSERT_COND(status == OS_SUCCESS);
status = osEventQueueCreate(Q, SIZE);




SmartDSP OS User Guide                                                                               71
Kernel Components
Events

OS_ASSERT_COND(status == OS_SUCCESS);

            The following code snippet (Listing 2.16) illustrates an example of a task pointing to a
            queue, another task pending on it, and an interrupt handler accepting it:

Listing 2.16 Tasks pointing to and pending on a queue

status = osEventQueuePend(Q, &message, TIMEOUT);                                    //Task 1

status = osEventQueuePost(Q, message, &resumed_task);                             // Task 2
OS_ASSERT_COND(status == OS_SUCCESS);

status = osEventQueueAccept(Q, &message);                                 //Interrupt Handler

            The functions available in the event queues module of the SmartDSP OS are listed in
            Table 2.9.

Table 2.9 Functions Available for Event Queues

             Flow State                    Name                           Description

             Kernel bring up                                              Already handled by the
                                                                          Events ‘base class’.

             Application bring up          osEventQueueFind()             Receives a handle to
                                                                          create a queue event.

                                           osEventQueueCreate(            Creates a queue event.
                                           )                              Initializes a queue and an
                                                                          empty waiting list. Then, it
                                                                          places a handle to this
                                                                          queue and to the empty
                                                                          waiting list in an event
                                                                          structure.




72                                                                       SmartDSP OS User Guide
Kernel Components
                                                                                    OS Tick Timers

Table 2.9 Functions Available for Event Queues (continued)

             Flow State                     Name                        Description

             Application runtime            osEventQueuePend()          Pends on an event queue
                                                                        if queue is empty;
                                                                        otherwise, dequeues and
                                                                        continues.

                                            osEventQueueAccept(         Continues without
                                            )                           pending. It checks if there
                                                                        is a message available in
                                                                        the queue. If there is a
                                                                        message, it returns the
                                                                        message to the caller.

                                            osEventQueuePost()          Posts a message to a
                                                                        queue. If tasks are
                                                                        pending on the queue, it
                                                                        posts messages on the
                                                                        tasks and schedules them;
                                                                        otherwise, enqueues.

                                            osEventQueueReset()         Removes all tasks pending
                                                                        on the queue and
                                                                        schedules them if they are
                                                                        ready.

             Application tear down          Not supported



OS Tick Timers
            In the devices incorporating DSP subsystems with the SC3400 core and above, such as
            MSC814x and later, the tick functionality runs on timer zero on each individual DSP
            subsystem. The timer expiration triggers a hardware interrupt which activates a software
            interrupt.
            The OS provides #define constants for standard tick resolutions in smartdsp_os_device.h.
            Refer to SmartDSP OS API Reference Manual for details.


            Configuration of OS Tick Timers
            The tick functionality is defined in os_config.h as:
            #define OS_TICK           ON
            #define OS_TICK_PRIORITY                OS_SWI_PRIORITY0



SmartDSP OS User Guide                                                                                73
Kernel Components
Software Timers

            #define OS_TICK_PARAMETER MSC814X_TICK_DEFAULT
            The #define constant for tick period is calculated by the number of interrupts per second.
            Therefore, for 10[ms] period that would be (10^3)/10 or:
            #define MSC815X_TICK_010MS                INTERRUPTS_PER_SEC_100
            #define INTERRUPTS_PER_SEC_100               100
            For example, if the intended tick period is 7[ms], the number of ticks per second and the
            OS_TICK_PARAMETER will be (10^3)/7 or 142.85. This number will be rounded down
            to 142 by the compiler since the kernel expects a uint32_t for the parameter.
            The DSP subsystem timer is configured by osTickIntProgram():
            divider_value = g_core_clock*1000000/g_tick_parameter;
            Since the g_tick_parameter will be rounded off, the calculation comes to, 1000*1000000/
            142 which is equal to 0x6B74CD or 7042253. Having a 1Ghz (ergo the 1000) count to this
            number will give 7.042253[ms].

            NOTE       g_tick_parameter is the equivalent of OS_TICK_PARAMETER and will
                       be rounded down by the compiler (defined as a uint32_t).


            NOTE       This is the current implementation and prone to change. For tick frequency
                       guarantee users must use the MSC81XX_TICK_XXXMS macros defined in
                       smartdsp_os_device.h.



Software Timers
            The software timers component of the SmartDSP OS kernel supports runtime association
            of software timer handlers, written in C or a C callable language. Software timers use the
            hardware tick timer as its point of reference. All software timer handlers run from the OS
            SWI assigned to the tick timer.
            The software interrupt handler checks the software timers, which are scheduled to expire
            on this tick, and calls their handler. Because software timers run as software interrupts,
            they are not as precise as hardware timers. Software timer handlers run in an interrupt (that
            is, system) context with the interrupt stack.
            You can enable and disable individual software timers, and set and change timer periods
            in the OS configuration file. At creation, a timer is specified as a one-shot timer or a
            periodic timer.
            A one-shot timer runs the associated timer function when the timer expires and does not
            run again. A periodic timer reloads its interval value each time the handler runs, and runs




74                                                                        SmartDSP OS User Guide
Kernel Components
                                                                                      Software Timers

            periodically. You can define the maximum number of software timers allowed by the
            system in the configuration file.
            Software timers have the granularity of the tick. A higher tick frequency allows better
            precision of software timers. A lower tick frequency causes less interrupt overhead on the
            core.
            Software timers require the tick functionality in the system that is defined in os_config.h,
            see Configuration of OS Tick Timers.


            Configuration of Software Timers
            The availability of software timers in the system is also configured in os_config.h as:
            #define OS_TOTAL_NUM_OF_SW_TIMERS                     5
            The functions available for the software timers module of the SmartDSP OS are listed in
            Table 2.10.

Table 2.10 Functions Available for Software Timers

             Flow State                   Name                                Description

             Kernel bring up (the user    osTimerInitialize()                 Initializes the software
             application does not call                                        timers module.
             these functions
             specifically. Instead,
             osInitialize() calls
             these functions based on
             the parameters from
             os_config.h and
             configurations from
             msc81xx_config.c)

             Application bring up         osTimerFind()                       Finds the first available
                                                                              software timer number.

                                          osTimerCreate()                     Creates a software
                                                                              timer and sets its
                                                                              parameters, such as
                                                                              timer number, timer
                                                                              mode, timer interval,
                                                                              and handler.

             Application runtime          osTimerStart() or                   Starts the given
                                          osTimerStartDelayed()               software timer.




SmartDSP OS User Guide                                                                                    75
Kernel Components
Software Timers

Table 2.10 Functions Available for Software Timers (continued)

             Flow State                    Name                                Description

                                           osTimerStop()                       Stops the given
                                                                               software timer.

                                           osTimerSetInterval()                Sets the interval of the
                                                                               given software timer.

                                           osTimerSelf()                       Retrieves the number of
                                                                               the currently active
                                                                               software timer.

             Application tear down         osTimerDelete()                     Deletes the given
                                                                               software timer from the
                                                                               system.


            The source code in Listing 2.17 dynamically creates a timer using osTimerFind(). The
            new timer expires only once (OS_TIMER_ONE_SHOT). The timer expires after five
            system ticks. When the timer is created, it does not start automatically. The next part of the
            listing starts the timer using osTimerStart().

Listing 2.17 Dynamically creating a one-shot timer

os_timer_handle timer1;
status = osTimerCreate(timer1,                                                 // timer object
                        OS_TIMER_ONE_SHOT,                                    // timer mode
                        5,                                                   // ticks timeout
                        timerTest1);                                        // timer handler
if (status != OS_SUCCESS) OS_ASSERT;

// Start the timer
status = osTimerStart(timer1);
if (status != OS_SUCCESS) OS_ASSERT;

void timerTest1()
{
// Do something...
}

            Listing 2.18 uses the previous timer, changes the tick timeout from 5 to 10, and restarts the
            timer for a single expiration.

Listing 2.18 Changing the timeout period of the timer

// Set the timer's timeout

76                                                                         SmartDSP OS User Guide
Kernel Components
                                                                                      Software Timers

status = osTimerSetInterval(timer1, 10);
if (status != OS_SUCCESS) OS_ASSERT;

// Start the timer
status = osTimerStart(timer1);

if (status != OS_SUCCESS) OS_ASSERT;

             Listing 2.19 dynamically creates a timer using osTimerFind(). The new timer expires
             repetitively because it is a periodic timer. The timer expires every time 20 system ticks
             elapse. When the timer is created, it does not start automatically. The next part of the
             listing starts the timer. To stop a timer, use the osTimerStop() function.

Listing 2.19 Dynamically creating a periodic timer

os_timer_handle timer2;
status = osTimerCreate(timer2,                // timer object
                        OS_TIMER_PERIODIC,   // timer mode
                        20,                 // ticks timeout
                        timerTest2);       // timer handler

if (status != OS_SUCCESS) OS_ASSERT;

// Start the timer
status = osTimerStart(timer2);

if (status != OS_SUCCESS) OS_ASSERT;
void timerTest2(void)
{
// Do something else...
}

// Stop the timer
status = osTimerStop(timer2);
if (status != OS_SUCCESS) OS_ASSERT;

             Listing 2.20 dynamically creates a timer using osTimerFind(). The new timer expires once
             because it is a one-shot timer. The timer expires after 20 system ticks elapse. When the
             timer is created it does not start automatically. The timer handler deletes the timer.

Listing 2.20 Dynamically creating a one-shot timer that deletes itself after it expires

os_timer_handle timer3

osTimerFind(&timer3);
status = osTimerCreate(timer3,                                      // timer object


SmartDSP OS User Guide                                                                                   77
Kernel Components
Hardware Timers

                              OS_TIMER_ONE_SHOT,               // timer mode
                              20,                             // ticks timeout
                              timerTest3);                   // timer handler

if (status != OS_SUCCESS) OS_ASSERT;

// Start the timer
status = osTimerStart(timer3);
if (status != OS_SUCCESS) OS_ASSERT;

void timerTest3()
{
os_timer_handle self;

// Delete the timer
status = osTimerSelf(&self);
if (status != OS_SUCCESS) OS_ASSERT;

status = osTimerDelete(self);
if (status != OS_SUCCESS) OS_ASSERT;

}




Hardware Timers
           The hardware timers are a group of timers running at system (not core) frequency. The
           hardware timers are shared among all cores and their sharing is handled by the SmartDSP
           OS drivers. Hardware timers are part of the SoC. The SoC hardware timer module
           contains four quadrates of four timers each. In devices with four cores, each core owns a
           quadrate. In devices with six cores, each core owns half a quadrate. This means that there
           are four hardware timers not enabled by the OS
           The hardware timers in the 8144/8156 processors are 16-bit timers which can be clocked
           from multiple optional input clocks. In 8144/8156 processors, there are four quadrates of
           clocks that make a total of sixteen 16-bit clocks.
           The SmartDSP OS supplies hardware timer implementation for the different architectures,
           wrapped with a common, minimal API. Hardware timers exist on most underlying
           hardware and work in a similar way.
           The SmartDSP OS API for hardware timers is similar to the software timers API, except
           that you must specify the clock source for the timer when they are created. Hardware
           timers have a finer granularity than the OS clock because they do not need to be tied to the
           OS clock. Hardware timers have the granularity of the driving clock, based on SoC
           support.



78                                                                       SmartDSP OS User Guide
Kernel Components
                                                                                    Hardware Timers


            Configuration of Hardware Timers
            The availability of hardware timers in the system is configured in os_config.h, as:
            #define OS_HW_TIMERS             ON
            The functions available for the hardware timers module of the SmartDSP OS are listed in
            Table 2.11.

Table 2.11 Functions Available for Hardware Timers

             Flow State                   Name                         Description

             Kernel bring up (the user    osHWTimerInitializ           Initializes the hardware
             application does not call    e()                          timers module.
             these functions
             specifically. Instead,
             osInitialize() calls
             these functions based on
             the parameters from
             os_config.h and
             configurations from
             msc81xx_config.c)

             Application bring up         osHWTimerFind()              Finds the first available
                                                                       hardware timer number.

                                          osHWTimerCreate()            Creates a hardware timer
                                                                       and sets its parameters,
                                                                       such as timer number, timer
                                                                       mode, clock source, timer
                                                                       interval, handler, and priority.

             Application runtime          osHWTimerStart()             Starts the given hardware
                                                                       timer.

                                          osHWTimerStop()              Stops the given hardware
                                                                       timer.

                                          osHWTimerSetInterv           Creates a hardware timer
                                          al()                         and sets its parameters.

                                          osHWTimerClearEven           Clears the event bit of the
                                          t()                          given hardware timer.


            Hardware timers can be set as OS_TIMER_ONE_SHOT, OS_TIMER_PERIODIC or
            OS_TIMER_FREE_RUN. When the timer expires, an application defined handler (set in
            osHwTimerCreate) is called.



SmartDSP OS User Guide                                                                                79
Kernel Components
Hardware Timers


           NOTE   OS does not call osHwTimerClearEvent function. The application
                  defined handler must call this function in order to clear the interrupt.




80                                                                 SmartDSP OS User Guide
3
Hardware Abstraction
Layers (HAL)
           This chapter explains Hardware Abstraction Layers (HAL). A HAL allows an application
           to stream Input/Output (I/O) data to a hardware device using device's Low Level Driver
           (LLD).

           NOTE       In SmartDSP OS, a HAL is also referred to as an Abstraction Module.

           This chapter consists of the following topics:
             • HAL in SmartDSP OS
             • Buffered I/O (BIO) Module
             • Coprocessor (COP) Module
             • Synchronized I/O (SIO) Module
             • Character I/O (CIO) Module


HAL in SmartDSP OS
           This topic explains the conceptual model and workflow of HAL in the SmartDSP OS.
           This topic consists of the following sub-topics:
             • Conceptual Model
             • Conceptual Workflow


           Conceptual Model
           HAL in the SmartDSP OS consists of two layers:
             • Serializer
                The serializer interacts with the user application to stream I/O data to a hardware
                device. The SmartDSP OS implements different serializer modules for different
                types of I/O data and different hardware devices. Each serializer module provides a
                high-level API to the user application for interacting with the corresponding LLD/
                hardware device.


SmartDSP OS User Guide                                                                           81
Hardware Abstraction Layers (HAL)
HAL in SmartDSP OS

                Table 3.1 lists the supported serializer modules and their functionality in the
                SmartDSP OS.
              • LLD
                The LLD interacts with the actual hardware device to perform I/O operations. The
                LLD uses LLD API to communicate with serializer.
Table 3.1 Serializer Modules in SmartDSP OS

             Serializer Module Name                       Functionality

             Buffered I/O (BIO) Module                    Supports the hardware devices, such as
                                                          Ethernet, that transmit and receive data
                                                          using data packets

             Coprocessor (COP) Module                     Supports co-processors, such as MAPLE

             Synchronized I/O (SIO) Module                Supports the hardware devices, where
                                                          both the transmit and the receive
                                                          processes are timed by the hardware,
                                                          such as TDM

             Character I/O (CIO) Module                   Supports character and stream oriented
                                                          devices, such as UART



           Figure 3.1 shows the conceptual model of HAL in the SmartDSP OS.

Figure 3.1 Conceptual Model of HAL in SmartDSP OS




82                                                                       SmartDSP OS User Guide
Hardware Abstraction Layers (HAL)
                                                                       Buffered I/O (BIO) Module



           The user application calls the hardware-independent high-level API functions, and the
           LLD implements the device specific functionality.


           Conceptual Workflow
           Figure 3.2 shows the conceptual workflow of an application using HAL in the SmartDSP
           OS to send and receive data to a hardware device.

Figure 3.2 Conceptual Workflow of HAL in SmartDSP OS




           NOTE       A channel is an abstract data path between the LLD and the hardware device.
                      All I/O operations use channels to send and receive data to a hardware device.
                      For duplex communication, two channels (transmit and receive) are required.



Buffered I/O (BIO) Module
           The BIO module provides high-level API and LLD for streaming I/O data to hardware
           devices, such as Ethernet, that transmit and receive data using data packets.
           The BIO module also performs serialization of transmitted and received data packets.
           This topic consists of the following sub-topics:
             • BIO Layers
             • BIO Initialization Workflow


SmartDSP OS User Guide                                                                             83
Hardware Abstraction Layers (HAL)
Buffered I/O (BIO) Module

               • BIO Runtime Workflow


            BIO Layers
            The BIO module consists of two layers:
               • BIO Serializer
                 BIO Serializer is the upper layer. It interacts with the user application using high-
                 level API, and performs serialization of the I/O data packets. Also, the upper layer
                 defines callback functions that the BIO module uses to pass the control back to the
                 user application.
               • BIO LLD
                 BIO LLD is the lower layer. It interacts with the actual BIO hardware device to
                 perform I/O operations. The BIO LLD for each BIO device must support the BIO
                 LLD API in the SmartDSP OS. For more information on the BIO LLD API, refer to
                 SmartDSP OS API Reference Manual.
            The BIO module uses a frame data structure to transfer the data between:
               • user application
               • BIO serializer
               • BIO LLD
            The SmartDSP OS API provides a SmartDSP OS frame data structure that you can use.
            You can also manage the frames using user-defined data structures.
            The user application should use the same data structure as used in the LLD frame data
            structure.


            BIO Initialization Workflow
            This topic explains the workflow of the BIO module during system (SmartDSP OS kernel)
            and user application initialization.
            This topic consists of the following sub-topics:
               • BIO Initialization Workflow - System (Kernel)
               • BIO Initialization Workflow - User Application


            BIO Initialization Workflow - System (Kernel)
            During system initialization:




84                                                                        SmartDSP OS User Guide
Hardware Abstraction Layers (HAL)
                                                                        Buffered I/O (BIO) Module

           1. the SmartDSP OS kernel initializes the LLD of all the BIO devices

           NOTE       Each LLD is initialized only once, even in a multi-core environment.

           2. the LLD initialization function initializes the corresponding hardware device
           3. the LLD initialization function registers the LLD with the BIO serializer
              The registration information contains function pointers that the BIO serializer uses to
              translate the high-level API functions to the corresponding LLD functions during
              application runtime.
           4. the number of BIO devices that the system supports is set using following definition in
              the os_config.h file:
              #define OS_TOTAL_NUM_OF_BIO_DEVICES 
                    (MSC815X_UEC0 + MSC815X_UEC1 + MSC815X_RIONET0 + 
                    MSC815X_RIONET1)
           5. the maximum number of channels, supported per BIO device, is set


           BIO Initialization Workflow - User Application
           During application initialization:
           1. BIO device is opened
              The user application calls the high-level API function, osBioDeviceOpen, to open
              a BIO device
           2. Tx/Rx channel in the BIO device is opened
              The user application calls the high-level API function, osBioChannelOpen, to
              open a Tx/Rx channel in the BIO device
           3. the memory required for the BIO channels is allocated
              You can allocate the memory by creating a static array of the bio_channel_t
              structure and specify the array size as the number of required channels.

           NOTE       The bio_channel_t structure defines the structure of a BIO channel. For
                      more information, refer to SmartDSP OS API Reference Manual.

           4. the number of queues are set
           The BIO serializer uses queues to hold transmitted and received frames.
             • For each BIO Tx channel, the BIO serializer uses Tx Confirmation Queue to hold the
               frames that are transmitted to the LLD. If the BIO serializer fails in transmitting a
               frame to the LLD, the BIO serializer notifies the user application, and does not put
               corresponding frame into the confirmation queue.


SmartDSP OS User Guide                                                                             85
Hardware Abstraction Layers (HAL)
Buffered I/O (BIO) Module

               • For each BIO Rx channel, the BIO serializer uses:
                 – one queue to hold the received frames
                 – another queue to hold the empty data buffers
                    The LLD must request empty data buffers from the BIO serializer before trying to
                    receive new data from the BIO device. The LLD can also choose a common
                    buffers pool for all the Rx channels.

            NOTE       The buffers pool consists of multiple chunks of memory, which the SmartDSP
                       OS memory manager maintains. The memory chunks are not stored in any
                       order.

                    When the LLD chooses a common buffers pool for the all the Rx channels, the
                    LLD gets empty buffers before having to identify the Rx channel.
                 Once the data is received into empty buffers, the LLD can choose one of these
                 options:
                 – let the BIO serializer build the received frames from the buffers (recommended)
                    The serializer builds a new frame structure according to the buffer length
                    (removing buffers from the buffers queue as needed), and puts the built frame
                    into the received frames queue.
                 – build the frames by itself; used for receiving extended frame structures that
                   contain additional information (other than the data buffers)
                    The LLD passes the pointer of the built frame to the BIO serializer. The serializer
                    only inserts the frame into the received frames queue.
                 In case of errors in the received data (for example, CRC errors), the frame is
                 discarded. The serializer does not build a new frame, but can notify the error using
                 application's receive callback function.
                To determine the number of queues that the BIO serializer requires, use the method
                that Table 3.2 explains.
Table 3.2 Determining the Number of Required Queues

              Operating Mode                              Number of Queues Required

              BIO serializer builds the frame, and no     BIO_dev_queues = num_of_tx_channels
              common buffers pool is used                 + (2*num_of_rx_channels)




86                                                                       SmartDSP OS User Guide
Hardware Abstraction Layers (HAL)
                                                                          Buffered I/O (BIO) Module

Table 3.2 Determining the Number of Required Queues (continued)

             Operating Mode                                Number of Queues Required

             BIO serializer builds the frame, and          BIO_dev_queues = num_of_tx_channels
             common buffers pool is used                   +1+
                                                           num_of_rx_channels_that_use_the_com
                                                           mon_pool +
                                                           (2*num_of_rx_channels_that_use_anoth
                                                           er_pool)

             LLD builds the frame, and any type of         BIO_dev_queues = num_of_tx_channels
             buffer pool is used                           + num_of_rx_channels


           BIO Runtime Workflow
           This topic explains the workflow of the BIO module during application runtime.
           This topic consists of the following sub-topics:
              • BIO Runtime Workflow - Transmit
              • BIO Runtime Workflow - Receive


           BIO Runtime Workflow - Transmit
           The BIO Tx channel must be open in the write mode, before the user application can
           transmit any data to a BIO device.
           The transmit process consists of the following steps:
           1. The user application uses the high-level API function, osBioChannelTx, and
              specifies a pointer to the Tx channel and a pointer to the frame that is to be transmitted.
           2. The serializer calls the LLD transmit function, and specifies the frame that is to be
              transmitted. In addition, the serializer queues the frame in Tx confirmation queue.
           3. The LLD transmits the frame to the BIO device.
           4. The LLD calls the LLD API function, bioChannelTxCb, and notifies the serializer
              about the number of transmitted frames.
           5. The serializer de-queues the specified frames from Tx confirmation queue.
           6. The serializer calls the transmit callback function of the user application, if any
              defined, for each transmitted frame. If the user application does not specify any
              transmit callback function, the serializer releases all the transmitted frames back to the
              frames pool.




SmartDSP OS User Guide                                                                                87
Hardware Abstraction Layers (HAL)
Coprocessor (COP) Module

           BIO Runtime Workflow - Receive
           The BIO Rx channel must be open in the read mode, before the user application can
           receive any data from a BIO device.
           The receive process consists of the following steps:
           1. The LLD requests an empty buffer from the BIO serializer for a specific Rx channel
              using the LLD API function, bioChannelRxBufferGet. The LLD can also
              request an empty buffer from a common buffers pool.
           2. The serializer allocates a new buffer to the LLD.
           3. The LLD replaces the old buffer with the new buffer, if the buffers use Buffer
              Descriptors (BD).
           4. The empty buffer receives the data.
           5. The LLD notifies the serializer using the LLD API function bioChannelRxCb, and
              specifies a pointer to the Rx channel and length of the received frame. The LLD may
              also build the frame by itself, and use the LLD API function,
              bioChannelRxFrameCb to notify the serializer.
           6. The serializer puts the received frame into the received frames queue.
           7. The serializer calls the receive callback function of the user application, if any defined,
              for each frame that is put into the received frames queue.
           8. The user application de-queues the frames from the received frames queue.


Coprocessor (COP) Module
           The COP module provides high-level API and LLD for dispatching jobs to a COP
           hardware device for execution.
           The SmartDSP OS currently supports SEC and MAPLE COP devices.

           NOTE       The COP module was introduced in MSC814x, and is not available for earlier
                      devices.

           The COP module also performs serialization of jobs.
           This topic consists of the following sub-topics:
             • COP Layers
             • COP Initialization Workflow
             • COP Runtime Workflow




88                                                                        SmartDSP OS User Guide
Hardware Abstraction Layers (HAL)
                                                                       Coprocessor (COP) Module


           COP Layers
           The COP module consists of two layers:
             • COP Serializer
                COP Serializer is the upper layer. It interacts with the user application using high-
                level API, and also performs serialization of jobs before dispatching to the COP
                device. In addition, the COP serializer ensures that job results are returned from the
                COP LLD to the user application in the order of dispatch.
             • COP LLD
                COP LLD is the lower layer. It interacts with the actual COP device to dispatch jobs.
                The COP LLD for each COP device must support the COP LLD API in the
                SmartDSP OS. For more information on COP LLD API, refer to SmartDSP OS API
                Reference Manual.

           NOTE       Generally, jobs dispatched to a COP device begin and terminate within the
                      device itself.



           COP Initialization Workflow
           This topic explains the workflow of the COP module during system (SmartDSP OS
           kernel) and while user application initialization.
           This topic consists of the following sub-topics:
             • COP Initialization Workflow - System (Kernel)
             • COP Initialization Workflow - User Application


           COP Initialization Workflow - System (Kernel)
           During system initialization:
           1. the COP device is registered with the COP serializer using the LLD API function,
              copRegister
              The registration information contains function pointers that the COP serializer uses to
              translate the high-level API functions to the corresponding LLD functions during
              application runtime.
           2. the number of COP devices that the system supports is set using following definition in
              the os_config.h file:
              #define OS_TOTAL_NUM_OF_COP_DEVICES 
                    (MSC815X_SEC + MAPLE + MAPLE_TVPE + MAPLE_FFTPE + 
                    MAPLE_DFTPE + MAPLE_CRCPE)


SmartDSP OS User Guide                                                                              89
Hardware Abstraction Layers (HAL)
Coprocessor (COP) Module

           3. the maximum number of channels, supported per COP device, is set


           COP Initialization Workflow - User Application
           During application initialization:
           1. COP device is opened
              The user application calls the high-level API function, osCopDeviceOpen, to open
              a COP device.
           2. COP channel in the COP device is opened
              The user application calls the high-level API function, osCopChannelOpen, to
              open a COP channel in the COP device.
           3. the memory required for the COP channels is allocated
              You can allocate the memory by creating a static array of the cop_channel_t
              structure and specify the array size as the number of required channels.

           NOTE       The cop_channel_t structure defines the structure of a COP channel. For
                      more information, refer to SmartDSP OS API Reference Manual.

           4. the total number of queues, one for each channel, is set in the os_config.h file
              using the OS_TOTAL_NUM_OF_QUEUES definition


           COP Runtime Workflow
           This topic explains the workflow of the COP module during application runtime.
           This topic consists of the following sub-topics:
             • COP Runtime Workflow - Job Dispatch

           NOTE       There is no receive path in the COP module.



           COP Runtime Workflow - Job Dispatch
           The COP Tx channel must be open in the write mode, before the user application can
           dispatch any jobs to a COP device.
           The transmit process consists of the following steps:
           1. The user application uses the high-level API function, osCopChannelDispatch,
              and specifies a pointer to a valid COP channel and a pointer to an array of job handles.
           2. The dispatch request is assigned to the COP LLD.




90                                                                      SmartDSP OS User Guide
Hardware Abstraction Layers (HAL)
                                                                    Synchronized I/O (SIO) Module

           3. The LLD calls the LLD API function, copChannelDispatchCb, and notifies the
              serializer that dispatched job has finished executing.
           4. The serializer calls the callback function of the user application, if any defined.


Synchronized I/O (SIO) Module
           The SIO module provides high-level API and the LLD for streaming I/O data to hardware
           devices, such as TDM, where both the transmit and the receive processes are timed by the
           hardware.
           The SIO module also performs serialization of transmitted and received data buffers.
           This topic consists of the following sub-topics:
             • SIO Layers
             • SIO Initialization Workflow
             • SIO Runtime Workflow


           SIO Layers
           The SIO module consists of two layers:
             • SIO Serializer
                SIO Serializer is the upper layer. It interacts with the user application using high-
                level API, and performs serialization of the data buffers.
             • SIO LLD
                SIO LLD is the lower layer. It interacts with the actual SIO hardware device to
                perform I/O operations. The SIO LLD for each SIO hardware device must support
                the SIO LLD API in the SmartDSP OS. For more information on SIO LLD API,
                refer to SmartDSP OS API Reference Manual.
           Using SIO is recommended when the hardware device uses a cyclic buffer, which may be
           divided into smaller sub-buffers, to transmit and receive data during specific time slots.
           This approach imposes hard real-time constraints on the user application, for example:
             • an under-run error, if the user application does not free the buffer, and if it is seized
             • unused time slot, if the user application does not provide any data for transmission
               during the specified time slot


           SIO Initialization Workflow
           This topic explains the workflow of the SIO module during system (SmartDSP OS kernel)
           and while user application initialization.


SmartDSP OS User Guide                                                                                  91
Hardware Abstraction Layers (HAL)
Synchronized I/O (SIO) Module

            This topic consists of the following sub-topics:
              • SIO Initialization Workflow - System (Kernel)
              • SIO Initialization Workflow - User Application


            SIO Initialization Workflow - System (Kernel)
            During system initialization:
            1. the SmartDSP OS kernel initializes the LLD of all the SIO devices

            NOTE       Each LLD is initialized only once, even in a multi-core environment.

            2. the LLD initialization function initializes the corresponding hardware device
            3. the LLD initialization function registers the LLD with the SIO serializer
               The registration information contains function pointers that the SIO serializer uses to
               translate the high-level API functions to the corresponding LLD functions during
               application runtime.
            4. the number of SIO devices that the system supports is set using following definition in
               the os_config.h file:
               #define OS_TOTAL_NUM_OF_SIO_DEVICES 
                     (MSC815X_TDM0 + MSC815X_TDM1 + MSC815X_TDM2 + 
                     MSC815X_TDM4)
            5. the maximum number of channels, supported per SIO device, is set


            SIO Initialization Workflow - User Application
            During application initialization:
            1. SIO device is opened
               The user application calls the high-level API function, osSioDeviceOpen, to open
               a SIO device.
            2. Tx/Rx channel in the SIO device is opened
               The user application calls the high-level API function, osSioChannelOpen, to
               open a Tx/Rx channel in the SIO device.
               When the SIO serializer opens a channel, the serializer submits an array of buffers to
               the LLD memory, and a reference to an index in the array of buffers. The LLD
               maintains an index of the current buffer and returns its reference to the user
               application. The serializer maintains an index of the buffer currently held by the user
               application. By comparing the LLD's index with the user application's index, the



92                                                                       SmartDSP OS User Guide
Hardware Abstraction Layers (HAL)
                                                                        Character I/O (CIO) Module

              serializer knows if an under-run occurred and if there is a new buffer that is ready to be
              passed to the user application.
           3. the memory required for the SIO channels is allocated
              You can allocate the memory by creating a static array of the sio_channel_t
              structure and specify the array size as the number of required channels.

           NOTE       The sio_channel_t structure defines the structure of a SIO channel. For
                      more information, refer to SmartDSP OS API Reference Manual.



           SIO Runtime Workflow
           This topic explains the workflow of the SIO module during application runtime.
           A SIO channel must be open in the write or read mode, before the user application can
           transmit or read any data to a SIO device.
           The transmit/read process consists of the following steps:
           1. The user application uses the high-level API function, osSioBufferGet, and
              receives a buffer and a buffer length from the Tx (write) or Rx (read) channel. The
              requested buffer is available to the user application as long as the buffer is not
              requested by the LLD. If the LLD requests the buffer while the user application is still
              using it, the serializer calls the application under-run callback and the buffer is seized
              from the user application.
           2. The user application:
                  • fills the buffer with the data if the buffer belongs to a Tx channel, and notifies
                    the serializer to increment its index
                  • reads the buffer if it belongs to a Rx channel, and the LLD increments its index
           3. The user application uses the high-level API function, osSioBufferPut, and
              returns the buffer to the LLD


Character I/O (CIO) Module
           The CIO module provides high-level API and LLD for streaming I/O data to hardware
           devices, such as UART, that transmit and receive data as a stream of characters/bytes.
           The CIO module also performs serialization of transmitted and received stream of
           characters.
           This topic consists of the following sub-topics:
             • CIO Layers
             • CIO Initialization Workflow


SmartDSP OS User Guide                                                                               93
Hardware Abstraction Layers (HAL)
Character I/O (CIO) Module

               • CIO Runtime Workflow


            CIO Layers
            The CIO module consists of two layers:
               • CIO Serializer
                 CIO Serializer is the upper layer. It interacts with the user application using high-
                 level API, and performs serialization of the I/O stream of characters.
               • CIO LLD
                 CIO LLD is the lower layer. It interacts with the actual CIO hardware device to
                 perform I/O operations. The CIO LLD for each CIO device must support the CIO
                 LLD API in the SmartDSP OS. For more information on CIO LLD API, refer to
                 SmartDSP OS API Reference Manual.


            CIO Initialization Workflow
            This topic explains the workflow of the CIO module during system (SmartDSP OS kernel)
            and user application initialization.
            This topic consists of the following sub-topics:
               • CIO Initialization Workflow - System (Kernel)
               • CIO Initialization Workflow - User Application


            CIO Initialization Workflow - System (Kernel)
            During system initialization:
            1. the SmartDSP OS kernel initializes the LLD of all the CIO devices.

            NOTE       Each LLD is initialized only once, even in a multi-core environment.

            2. the LLD initialization function initializes the corresponding hardware device.
            3. the LLD initialization function registers the LLD with the CIO serializer.
               The registration information contains function pointers that the CIO serializer uses to
               translate the high-level API functions to the corresponding LLD functions during
               application runtime.




94                                                                        SmartDSP OS User Guide
Hardware Abstraction Layers (HAL)
                                                                      Character I/O (CIO) Module

           4. the number of CIO devices that the system supports is set using following definition in
              the os_config.h file:
              #define OS_TOTAL_NUM_OF_CIO_DEVICES 
                    (MSC815X_DOORBELL + MSC815X_UART + MSC815X_I2C + 
                    MSC815X_SPI)
           5. the maximum number of channels, supported per CIO device, is set.


           CIO Initialization Workflow - User Application
           During application initialization:
           1. CIO device is opened
              The user application calls the high-level API function, osCioDeviceOpen, to open
              a CIO device.
           2. Tx/Rx channel in the CIO device is opened
              The user application calls the high-level API function, osCioChannelOpen, to
              open a Tx/Rx channel in the CIO device.
              When the CIO serializer opens a channel, the user application sends a character array
              to the serializer. The serializer assigns this character array to both Tx and Rx CIO
              channels.
           3. the memory required for the CIO channels is allocated
              You can allocate the memory by creating a static array of the cio_channel_t
              structure and specify the array size as the number of required channels.

           NOTE       The cio_channel_t structure defines the structure of a CIO channel. For
                      more information, refer to SmartDSP OS API Reference Manual.



           CIO Runtime Workflow
           This topic explains the workflow of the CIO module during application runtime.
           The CIO serializer uses two dynamic pointers to transmit/receive the stream of characters:
             • one pointer points to the current transmitted/received data
             • another pointer points to the next free location at which the new data will be
               transmitted/received
           This topic consists of the following sub-topics:
             • CIO Runtime Workflow - Transmit
             • CIO Runtime Workflow - Receive



SmartDSP OS User Guide                                                                            95
Hardware Abstraction Layers (HAL)
Character I/O (CIO) Module

            CIO Runtime Workflow - Transmit
            The CIO Tx channel must be open in the write mode, before the user application can send
            a stream of characters to a CIO device.
            The transmit process consists of the following steps:
            1. The user application uses the high-level API function, osCioChannelBufferGet,
               and receives a pointer to a free buffer.
            2. The user application fills the buffer with the data, and uses the high-level API function,
               osCioChannelTxBufferPut, to notify the serializer that the data is ready for
               transmission.
            3. The serializer calls the LLD transmit function.
            4. The LLD transmits the data to the CIO device.
            5. The LLD calls the LLD API function, cioChannelTxCb, and notifies the serializer
               about the number of transmitted bytes.
            6. The serializer calls the transmit callback function of the user application, if any
               defined, for each transmitted buffer of data.

            NOTE       Every osCioChannelBufferGet call must have a corresponding
                       osCioChannelTxBufferPut call, or else the serialization process may
                       lead to corrupt data.



            CIO Runtime Workflow - Receive
            The CIO Rx channel must be open in the read mode, before the user application can read a
            stream of characters from a CIO device.
            The receive process consists of the following steps:
            1. The LLD uses the high-level API function, osCioChannelBufferGet, and
               receives a pointer to a free buffer.
            2. The CIO device sends an interrupt to the LLD, and the LLD fills the buffer with the
               received data.
            3. The LLD calls the LLD API function, cioChannelRxCb, and notifies the serializer
               that the data is received.
            4. The serializer calls the receive callback function of the user application, if any defined,
               for each received buffer of data.
            5. The user application uses the high-level API function,
               osCioChannelRxBufferGet, and receives a pointer to the received data.




96                                                                         SmartDSP OS User Guide
Hardware Abstraction Layers (HAL)
                                                                Character I/O (CIO) Module

           6. The user application uses the high-level API function,
              osCioChannelRxBufferFree, and notifies the serializer that the data processing
              is finished.

           NOTE      Every osCioChannelRxBufferGet call must have a corresponding
                     osCioChannelRxBufferFree call, or else the serialization process may
                     lead to corrupt data.




SmartDSP OS User Guide                                                                   97
Hardware Abstraction Layers (HAL)
Character I/O (CIO) Module




98                                  SmartDSP OS User Guide
4
Drivers
           A driver program allows SW, which utilizes the OS, to interact with a peripheral device.
           The SmartDSP OS,
             • supports a unified, cross-device API for generic HW drivers;
             • provides a device-specific API for device-specific HW; and,
             • supports MSC814x, MSC815x, and MSC825x processor driver families.
           The five SmartDSP OS driver types are noted in the below table.
Table 4.1 SmartDSP Drivers

            Driver                    Description                      Example

            DMA                       Provides a unified API.           • DMA controllers

            BIO                       Provides a unified API for all    • ETH messages
                                      frame type drivers.               • RapidIO®
                                                                          messages

            COP                       Provides a unified API for all    • SEC and MAPLE-
                                      co-processors.                      B

            SIO                       Provides a unified API for        • TDM
                                      devices with HW-timed Rx/
                                      Tx processes.

            CIO                       Provides a unified API for        • UART and I²C
                                      non frame-based devices
                                      (that lack a logical division
                                      of the data into frames or
                                      packets).



           This chapter has sections detailing the following SmartDSP OS drivers:
             • Direct Memory Access (System DMA)demosstarcoremsc815xuart
             • OCeaN DMA
             • QUICC Engine Unified Ethernet Controller (QE UEC)
             • Serial RapidIO (sRIO)
             • Doorbell



SmartDSP OS User Guide                                                                           99
Drivers
Direct Memory Access (System DMA)

             • PCI Express (PCIe)
             • Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)
             • RIONET
             • Time Division Multiplexing (TDM)
             • Universal Asynchronous Receiver/Transmitter (UART)


Direct Memory Access (System DMA)
           A System DMA is a HW controller; it off loads, from the core, the task of moving data
           from one location to another.
           SmartDSP OS provides a unified, cross-platform API for the System DMA driver and,
           where necessary, a platform-specific API.


           Features
           SmartDSP OS System DMA LLD features are noted below.
             • Full exposure of all HW features.
             • Functions inlined for performance gain.
             • Generic and SoC-specific APIs.
             • Ability to pre-program BD rings (chains).
             • Ability to modify existing BDs (transfer/buffer).
             • Interrupt/polling at job completion.
             • Assignment of channels-to-cores at compilation time.


           Architecture
           This section covers the SW architecture of the System DMA driver.


           Driver Components
           This section details System DMA driver components found in the SmartDSP OS. See
           Table 4.2 and Figure 4.1 for further details.




100                                                                   SmartDSP OS User Guide
Drivers
                                                       Direct Memory Access (System DMA)



Table 4.2 System DMA Components

            Components        Description

            Controller          • Represents the actual HW block.
                                • HW block acts as follows:
                                 – generates access to the system bus;
                                 – manages data transfers between memory and HW devices;
                                   and
                                 – manages multiple channels.
                                • Each channel can be programmed to move data from
                                  one place to another, independent of other channels.

            Channel             • Represents the actual HW channel for data transfers.
                                • Executes chains of DMA transfers.
                                • Handles interrupts generated by DMA transfers.
                                • Pre-allocated to a given core at compilation time.

            Chain               • Represents a BD ring.
                                • BD ring assembles DMA transfers in a BD chain.
                                • Can be inactive.
                                • Executable by any channel.

            Transfer/Buffer     • Represents a BD; each BD describes DMA transaction
                                  attributes.

                              Transfer
                                • Symmetric 1D (classic) DMA transaction.
                                • Includes all related R/W transaction attributes.

                              Buffer
                                • Representation of a specific HW DMA BD
                                  implementation.
                                • Describes R/W transaction attributes of 1D or more.
                                • Can include other HW-specific features.
                                • See SmartDSP OS API Reference Manual.




SmartDSP OS User Guide                                                                      101
Drivers
Direct Memory Access (System DMA)

Figure 4.1 System DMA Module Structure




           Design Decisions
           Design decisions, along with their reasoning, are noted below.
           1. The System DMA driver does not support cycle consuming cache and virtual
              addressing operations in the LLD.
              • Driver was written to minimize runtime overhead.
              • Driver API enables runtime modifications of pre-programmed BDs.
           2. Many System DMA driver functions are statically inlined.
              • Minimizes the number of function calls as well as driver overhead.
           3. Assigning channels-to-cores occurs at compilation time.
              • Minimizes the driver’s program memory footprint.


           Data Flow
           This section outlines the runtime data flow.
           1. Application pre-configures one (or more) BD chains.
           2. Application attaches one of the chains to a channel and activates the channel.
           3. Channel chronologically iterates the BDs—in the order they were attached to the
              chain—and executes them.
           4. Every application-modifiable BD attribute is defined; they cannot be changed during
              execution.


102                                                                     SmartDSP OS User Guide
Drivers
                                                           Direct Memory Access (System DMA)

           5. Channel completes execution.
           6. Application reactivates a given chain, swaps it for another, or becomes idle.
           In System DMA implementations, as configured by the application, the channel can be
           frozen during chain execution. Later, the application can unfreeze the channel. See API.


           Programming Model
           This section covers driver bring-up—first by the OS, then by the application-chosen API.


           General
           The System DMA consists of two API families.
              • Generic DMA concept—API is prefixed with osDma.
              • Device-specific family—API is prefixed by the device name; e g., msc815xDma.
           See the SmartDSP OS API Reference Manual for a complete list of DMA LLD API.
           Table 4.3 describes both architecture-independent and dependent APIs.
Table 4.3 Architecture-Independent/Dependant APIs

             Architecture API               Functions                      Description

             Architecture-independent       Functions include:               • Uses
             API                                                               functions
                                              • osDmaChannelO                  regardless of
             (see Table 4.4)                    pen()                          the HW
                                              • osDmaChainCre                  architecture;
                                                ate()                          e.g., Works.

                                              • osDmaChannelB
                                                ind()

             Architecture-dependant API     Functions include:               • Uses
                                                                               functions
                                              • msc814xDmaCha                  when the HW
                                                nnelDefrost()                  cannot be
                                              • msc815xDmaCha                  used for all
                                                                               architectures;
                                                nnelDisable()
                                                                               e.g.,
                                                                               Common.
                                                                             • Header file:
                                                                               includear
                                                                               chstarcor
                                                                               emsc81xx
                                                                               msc81xx_dm
                                                                               a.h




SmartDSP OS User Guide                                                                           103
Drivers
Direct Memory Access (System DMA)

            Calling Sequence Example
            Table 4.4 describes functions included in the architecture-independent API of the
            SmartDSP OS DMA driver. The functions include kernel bring-up, application bring-up,
            application runtime, and application teardown.

Table 4.4 Architecture-Independent API

             State               Function                       Description

             Kernel Bring-up     osInitialize()->                 • User application does
                                 osArchDevicesInitialize()          not directly call these
                                 ->                                 functions.
                                 osDmaInitialize()                • osInitialize()
                                                                    calls
                                                                    osDmaInitialize(
                                                                    )— as based on
                                                                    os_config.h
                                                                    defines and
                                                                    msc81xx_config.c
                                                                    configuration
                                                                    structures.
                                                                  • Initializes System
                                                                    DMA driver.




104                                                                  SmartDSP OS User Guide
Drivers
                                                          Direct Memory Access (System DMA)

Table 4.4 Architecture-Independent API

             State                Function                     Description

             Application Bring-   osDmaControllerOpen()          • Must be first function
             up                                                    called.
                                                                 • Returns a DMA
                                                                   controller handle.
                                                                 • Handle is a parameter
                                                                   in calling other
                                                                   functions.
                                  osDmaChannelOpen()             • Opens a pre-allocated
                                                                   channel.
                                                                 • Initializes channel
                                                                   structure as per
                                                                   configuration
                                                                   parameters.
                                  osDmaChainCreate()             • Creates a DMA chain.
                                                                 • Initializes chain
                                                                   structure as per
                                                                   configuration
                                                                   parameters.
                                  osDmaChainTransferAdd()        • Adds a transfer to a
                                                                   DMA chain.
                                  osDmaChainTransferAddEx()      • Adds a transfer to a
                                                                   DMA chain.
                                                                 • Returns a handle to
                                                                   the transfer.
                                                                 • Handle can be used to
                                                                   modify transfer
                                                                   attributes.

             Application          osDmaChannelBind()             • Binds a chain to a
             Runtime                                               channel.

                                  osDmaChannelStart()            • Starts execution of a
                                                                   bound chain(s) on a
                                                                   DMA channel.
                                  osDmaChannelIsActive()         • Polls the DMA
                                                                   channel to check its
                                                                   state (active/idle).




SmartDSP OS User Guide                                                                       105
Drivers
Direct Memory Access (System DMA)

Table 4.4 Architecture-Independent API

             State                 Function                         Description

             Application           osDmaChainDelete()                 • Releases DMA chain
             Teardown                                                   resources (except
                                                                        memory).
                                                                      • Removes a chain from
                                                                        the DMA controller.
                                   osDmaChannelClose()                • Releases DMA
                                                                        channel resources
                                                                        (except memory).


            To populate a chain, the application can use the architecture-independent transfer concept,
            architecture-dependent buffer concept, or a combination of both.
            The buffer allows users to program each side (R/W) of the chain as an individual entity;
            this allows for a mix of HW-enabled features such as BD dimension, freeze dimension,
            etc. The application is responsible for balancing the number of DMA channel R/W bytes.
Table 4.5 Architecture-Dependent API

             State              Function                            Description

             Bring-up           msc815xDmaChainBufferAdd()             • Appends a buffer to a
                                                                         DMA chain.
                                msc815xDmaChainBufferAddEx(            • Appends a buffer and
                                )                                        returns a handle to a
                                                                         DMA chain.

             Runtime            msc815xDmaChannelFreeze()              • Freezes a DMA
                                                                         channel.
                                msc815xDmaChannelDefrost()             • Unfreezes a DMA
                                                                         channel.
                                msc815xDmaChannelDisable()             • Disables a DMA
                                                                         channel.



            NOTE        Common MSC814x and MSC815x architecture-specific features:
                        - share a similar API
                        - prefixed by the device name.




106                                                                      SmartDSP OS User Guide
Drivers
                                                          Direct Memory Access (System DMA)

           Functionality
           Initialization
           Follow these steps to initialize the DMA:
           1. Enable DMA support by setting #define MSC81XX_DMA ON in the application
              os_config.h file.
           2. Allocate memory; this enables the driver to handle a DMA channel.
              • User application determines memory size:
              /* Allocate memory for channel use. */
              uint8_t dma_channel[DMA_SIZE_OF_MEMORY_FOR_CHANNEL_USE];
           3. Allocate memory for a DMA chain handle. Allocation reflects both the DMA chain
              type and the maximum number of associated DMA transfers.
              • User application determines DMA chain, memory size:
                DMA_SIZE_OF_MEMORY_FOR_CHAIN_USE(<NUM_BUFFERS>)
              • Above code example allocates memory for a default chain type:
                /* Allocate memory for chain with two transfers. */
                 uint8_t dma_chain_memory[DMA_SIZE_OF_MEMORY_FOR_CHAIN_USE(2)];
           4. Get DMA controller handle using osDmaControllerOpen().
              • Function returns the handle to the driver-allocated DMA controller.
              • User application must retrieve this handle to open DMA channels and create DMA
                chains.
           5. Open controller DMA channel using osDmaChannelOpen().
           6. Create a DMA chain using osDmaChainCreate().
              • Chain is created using allocated memory, a parameter structure, and a DMA
                controller handle.
           7. Add DMA transfers to the DMA chain using osDmaChainTransferAdd() or
              osDmaChainTransferAddEx().
              • osDmaChainTransferAddEx() returns a handle to added transfers; this
                allows for attribute modification.

           Runtime
           Follow these steps to run DMA in the application.
           1. Reset or empty the DMA chain using osDmaChainReset(dma_chain).
           2. Program the DMA channel with the DMA chain using
              status = osDmaChannelBind(dma_channel, dma_chain);



SmartDSP OS User Guide                                                                      107
Drivers
Direct Memory Access (System DMA)


           NOTE       DMA channel and chain must be unbound when executing function,
                      status = osDmaChannelBind(dma_channel, dma_chain);

                      If, however, an application reprograms the DMA channel with the same DMA
                      chain then these conditions must be met:
                      – DMA chain parameter must be NULL.
                      – DMA channel must be bound using the following:
                        status = osDmaChannelBind(dma_channel, NULL);

           3. Start the DMA channel, after it is bound to a chain, using
              osDmaChannelStart().
           4. [Option] Poll a DMA channel using osDmaChannelIsActive() to check if the
              channel is active.
              – After completion of the DMA run and chain, the driver disables the interrupt.
              – Driver can be enabled at osDmaChannelOpen().
              – If the interrupt was enabled, the driver calls the interrupt handler with interrupt
              parameters specified in OsDmaChannelOpen().

           Free
           Follow these steps to enable DMA Free.
           1. Ensure DMA channel is inactive.
           2. Unbind DMA channel and chain using the function, osDmaChannelUnbind().
              • Indicates DMA chain can be deleted or bound to a different DMA channel.
              • Indicates DMA channel can be closed or bound to a different DMA chain.
           3. Release DMA channel using osDmaChannelClose().
              • Releases all DMA channel resources (except memory) that belong to a user
                application.
           4. Release DMA chain using osDmaChainDelete().
              • Releases all DMA channel resources (except memory) that belong to a user
                application.

           Performance Rules
           Performance Rules guidelines—for user applications—improve MSC814x and MSC815x
           System DMA performance.
             • Place BD close to Port A (one of two ports).
                – Port A is always used for BD fetch.
                – Rule is primarily applicable to MSC8144.



108                                                                    SmartDSP OS User Guide
Drivers
                                                                                      OCeaN DMA

             • Minimize WAR penalties on the SoC CLASS fabric.
                – Application should configure the System DMA to read from a port close to the
                  data source and write to the other port.
                – Rule is primarily applicable to MSC8144.
             • Consider target-switching when programming channels to access various targets.
             • Set BTSZ to the 64-byte maximum as part of the BD attribute.
             • Set TSZ to ‘high’ as per application requirements.


           Source Code
           SmartDSP OS DMA driver header files:
             • includecommonos_dma.h.
             • includearchstarcoremsc815xmsc815x_dma.h
             • initializationarchmsc815xincludemsc815x_dma_init.h
             • includearchstarcoremsc814xmsc814x_dma.h
             • initializationarchmsc814xincludemsc814x_dma_init.h


           Resource Management
           Minimize a driver’s data footprint by assigning channels-to-cores at compilation time.
             • Driver configures the master core (osGetMasterCore()) to handle error
               interrupts during osDmaInitialize() execution.
             • Driver handles HW-related errors.
             • User callback functions handle functional errors.


           Demo Use Cases
           SmartDSP OS DMA driver demos:
             • demosstarcoremsc814xdma_multicore
             • demosstarcoremsc815xdma_demo.


OCeaN DMA
           OCeaN DMA, also known as OCN DMA and On-chip Network DMA, is used to generate
           RapidIO and PCIe (MSC815x only) buses.




SmartDSP OS User Guide                                                                          109
Drivers
OCeaN DMA


            Features
            SmartDSP OS OCeaN DMA features are noted below.
              • OCeaN DMA is used to generate DMA accesses in the OCeaN fabric.
                – OCeaN fabric is a non-blocking, high-speed interconnect used for embedded
                  system devices.
              • Able to generate transactions towards HSSI peripherals (sRIO and PCIe).
              • Accesses OCeaN ports as per address ranges configured in its ATMU windows.
              • Generates accesses in a 36-bit address space.
                – Relies on the target OCean ATMU mechanism to resolve the actual address.
              • Address space limitations:
                – System (CLASS): 32 bits. System interface shortens four MSB; it does not
                  resolve addresses.
                – RapidIO: 34 bits. sRIO ATMU converts a 36-bit OCeaN address to a 34-bit sRIO
                  address.
                – PCIe (MSC815x only). PCIe ATMU can convert a 36-bit OCeaN address to
                  either a 32- or 64-bit PCIe address.
              • MSC814x supports a 34-bit ATMU bypass address space.
                – Makes write access part of the transfer description.
                – MSC815x has no HW support for ATMU address bypassing.


            Relevant SoC
            MSC8144
            MSC815x


            Architecture
            This section covers the SW architecture of the OCeaN DMA driver. The OCeaN fabric
            requires no programming and provides a seamless interface for the HSSI. See OCean
            DMA ArchitectureOCean DMA ArchitectureTable 4.6.




110                                                                      SmartDSP OS User Guide
Drivers
                                                                                    OCeaN DMA



Table 4.6 OCean DMA Architecture

            Processor                    Description

            MSC8144                         • One OCeaN DMA instantiation.
                                            • Also called sRIO DMA.
                                            • Only supports sRIO.

            MSC815x                         • Two OCeaN DMA instantiations.
                                            • Support sRIO and PCIe.



           NOTE       System DMA cannot be used to create transactions over I/O ports.



           Design Decisions
           Design decisions, along with their reasoning, are noted below.
           OCeaN and System DMA channels share two design decisions.
           1. OCeaN DMA driver does not support cycle consuming cache and virtual addressing
              operations in the LLD.
              • Driver was written to minimize runtime overhead.
              • Driver API enables runtime modifications of pre-programmed BDs.
           2. Assigning channels-to-cores occurs at compilation time.
              • Minimizes the driver’s program memory footprint.


           Calling Sequence Example
           Table 4.7 describes functions included in the SmartDSP OS OCeaN driver. The functions
           include kernel bring-up, application bring-up, application runtime, and application
           teardown.




SmartDSP OS User Guide                                                                      111
Drivers
OCeaN DMA


Table 4.7 OCeaN DMA API

            State                  Function                 Description

            os_config.h   file     #define                    • [MSC814x] OCeaN
                                   MSC814X_SRIO_DMA ON          DMA support

                                   #define                    • [MSC815x] OCeaN
                                   MSC815X_OCN_DMA0 ON          DMA support
                                   #define
                                   MSC815X_OCN_DMA1 ON

            Kernel Bring-up        osInitialize()->           • User application does
                                   osArchDevicesInitializ       not directly call these
                                   e()->                        functions.
                                   ocnDmaInitialize()         • osInitialize()
                                                                calls the noted
                                                                functions based on
                                                                os_config.h
                                                                defines and
                                                                msc81xx_config.c
                                                                configuration
                                                                structures.
                                                              • Initializes the OCeaN
                                                                DMA driver.

            Application Bring-up   ocnDmaControllerOpen()     • Must be first function
                                                                called.
                                                              • Returns an OCeaN
                                                                DMA controller
                                                                handle; handle is a
                                                                parameter in calling
                                                                other functions.
                                   ocnDmaChannelOpen()        • Opens a pre-
                                                                allocated channel.
                                                              • Initializes channel
                                                                structure as per
                                                                configuration
                                                                parameters.
                                   ocnDmaChainCreate()        • Creates an OCeaN
                                                                DMA chain.
                                                              • Initializes chain
                                                                structure as per
                                                                configuration
                                                                parameters.
                                   ocnDmaChainTransferAdd     • Adds a transfer to an
                                   ()                           OCeaN DMA chain.




112                                                             SmartDSP OS User Guide
Drivers
                                                                                   OCeaN DMA

Table 4.7 OCeaN DMA API (continued)

            State                  Function                   Description

            Application Runtime    ocnDmaChannelBind()           • Binds a chain to a
                                                                   channel.
                                   ocnDmaChannelStart()          • Starts execution of a
                                                                   bound chain(s) on an
                                                                   OCeaN DMA
                                                                   channel.
                                   ocnDmaChannelIsActive(        • Polls the OCeaN
                                   )                               DMA channel to
                                                                   check its state (active/
                                                                   idle).
                                   ocnDmaTransferWait()          • Waits for the release
                                                                   of a specific OCeaN
                                                                   DMA channel.

            Application            ocnDmaChainDelete()           • Releases OCeaN
            Teardown                                               DMA chain resources
                                                                   (except memory).
                                                                 • Removes a chain
                                                                   from the OCeaN DMA
                                                                   controller.
                                   ocnDmaChannelClose()          • Releases OCeaN
                                                                   DMA channel
                                                                   resources (except
                                                                   memory).



           Functionality
           Figure 4.2 shows an MSC8156 HSSI block diagram and illustrates the role of OCeaN
           DMA.




SmartDSP OS User Guide                                                                        113
Drivers
OCeaN DMA

Figure 4.2 MSC815x HSSI Block Diagram




            Source Code
            SmartDSP OS OCeaN DMA MSC814x and MSC815x driver header files for initialization
            and runtime:
              • initializationarchmsc814xincludemsc814x_srio_dma_init
                .h
              • includearchstarcoremsc814xmsc814x_srio_dma.h
              • initializationarchmsc815xincludemsc815x_ocn_dma_init.
                h
              • includearchstarcoremsc815xmsc815x_ocn_dma.h


            Demo Use Cases
            demosstarcoremsc814xrio_dma
            demosstarcoremsc815xrio_dma




114                                                               SmartDSP OS User Guide
Drivers
                                          QUICC Engine Unified Ethernet Controller (QE UEC)


QUICC Engine Unified Ethernet Controller
(QE UEC)
           Introduction
           The MSC814X and MSC815X QE controllers support two GETH UECs. Each controller
           supports several standard MAC-PHY interfaces that connect to an external Ethernet
           transceiver.


           Features
           Smart DSP OS System QE UEC features are noted below:
             • Packet filtering:
               – QE selects the target queue.
               – [Default] Packets are filtered and classified to queues as per MAC addresses.
             • Extended filtering and pattern matching options:
               – User overrides default filtering during initialization or runtime.
               – Driver configures the UEC to filter as per set patterns or packet fields; e.g., IP
                 address.
               – Applications provide additional runtime rules.
             • G/ETH UEC:
               – Default configuration for Ethernet support.
               – Override with uec_eth_params_t structure during UEC initialization.
               – MSC814x and MSC815x QE support two GETH UECs.
             • Controllers:
               – Support several standard MAC-PHY interfaces connecting to an external ETH
                 transceiver.
               – Have different UEC drivers.
               – Run at HW supported speeds and protocols (e.g., 1000Mbps SGMII, 100Mbps
                 RGMII).
             • Drivers:
               – Supports a maximum of eight Tx and Rx queues.
               – UEC HW and drivers support two behaviors (single- and multi-buffered frames)
                 that handle incoming packets with a payload larger than the QE-programmed
                 MTU.



SmartDSP OS User Guide                                                                            115
Drivers
QUICC Engine Unified Ethernet Controller (QE UEC)

              • Queue scheduling policy:
                – Driver enables configuring of UEC queues.
                – Supported scheduling policies: Strict Priority and Weighted Fair Queueing.
                – Channels/queues are prioritized and classified as per application requirements.
                – Configuration done at initialization or runtime.
              • UEC single-buffered frames:
                – [Default] Enables UEC single-buffered frames.
                – Functions defined at compilation time.
                – All packet contents must be placed in a single buffer; only one BD points to this
                  buffer. The BD passes packet information from HW to SW.
                – Buffer memory must have a maximum payload size.
                – Provides fast LLD and BIO execution.
              • UEC multi-buffered frames:
                – Functions are defined at compilation time.
                – Enable by setting definitions in the os_config.h at compilation time:
                  #define UEC0_MULTI_BUFFERED_FRAME
                  #define UEC1_MULTI_BUFFERED_FRAME
                – Fewer memory restrictions as buffer memory isn’t needed to achieve maximum
                  payload size.
                – Slower LLD/BIO execution.
                – Requires SmartDSP OS multi-buffered frames.
                – Allows for SmartDSP OS multi-buffered frames; however, faster executing
                  SmartDSP OS single-buffered frames are preferrable.
              • UEC configuration modes:
                – UEC supports several modes that are configured using flags passed in the
                  initialization strcuture:
                – UEC_CFG_LOOPBACK - UEC is configured to loopback mode.
                – UEC_CFG_ENABLE_STATISTICS - UEC gathers runtime statistics.
                – UEC_CFG_LOSSLESS_FLOW_CONTROL - Enables lossless-flow-control.
                – UEC_CFG_FORCE_LINK - osInitialize functions even without a connection.
              • Callback function functionality:
                – Enables direct and easy access to the net stack.
              • Asymmetric buffering on different UEC:
                – Identical buffering (single or multi) is not required for UEC0 and UEC1.


116                                                                    SmartDSP OS User Guide
Drivers
                                         QUICC Engine Unified Ethernet Controller (QE UEC)


           NOTE      See Hardware Abstraction Layers (HAL) for detailed BIO information.



           Relevant SoC
           SmartDSP OS Ethernet drivers support 8156 and 8144 Tx and Rx channels.


           Architecture
           This section covers the SW architecture of the UEC driver.


           Components
           This section details driver components found in the SmartDSP OS.
Table 4.8 QE UEC Components

            Components                Description

            Tx/Rx Queues                • Each UEC driver supports up to 8 Tx and 8 Rx
                                          queues modelled as a unidirectional software
                                          channel.
                                        • Queues provide filtering and scheduling
                                          capabillities.

            UEC Device Control          • UEC driver has device controls; they configure and
                                          change the state of the UEC and other device
                                          operations.
                                        • User calls the BIO abstraction layer that, in turn,
                                          calls uecCtrl() for the LLD.
                                      UEC_CMD_ENABLE                    Enable UEC.

                                      UEC_CMD_TX_RESTART                Resume UEC Tx operation.

                                      UEC_CMD_ENTER_PATTERNS            Pattern match programming.

                                      UEC_CMD_ADD_MCAST_ADDRES          Add address to UEC
                                      S                                 extended filtering.

                                      UEC_CMD_CONFIG_SCHEDULER          Configuration of UEC
                                                                        scheduler.

                                      UEC_CMD_STAT_GET                  Receive UEC-gathered
                                                                        statistics.




SmartDSP OS User Guide                                                                             117
Drivers
QUICC Engine Unified Ethernet Controller (QE UEC)

            Design Decisions
            Design decisions, along with their reasoning, are noted below.
            1. Each SW Tx and Rx channel is modelled as a unidirectional queue with filtering and
               scheduling capabilities.
            2. Driver implementation provides callback function functionality.
              • Enables easy access to the net stack.
            3. Driver is implemetned under the BIO abstraction layer.
              • User application calls BIO functions directly and UEC functions indirectly.
              • Creates certain uniformity among user applications; e.g., user must use the
                os_frame_t structure.


            Data Flow
            UEC driver supports both Rx (interrupt/polling) and Tx indications and can work in
            cooperation with the net stack.
            Transmit Flow
            If there is no interrupt then, after transmission, the previous Tx BD is checked for reuse.
            1. Driver receives a frame transmitted from the BIO layer; the frame has a pointer (to a
               buffer).
            2. Driver places the buffer on the BD ring.
            3. If the buffer is transmitted successfully then the driver releases the frame—unless
               there is a user-defined callback.
            Recieve Flow
            BIO Rx channel callback function can be set to etherInput()— a network stack input
            point. If the LLD channel is open then a user application can affect each Rx BD (in the BD
            ring).
            1. QE—upon receiving data—fills a buffer/s according to data size.
            2. BD ring status bit signals the driver that data was received (by polling or interrupt).
            3. Driver receives a signal then BIO takes a new buffer from the pool to replace a used
               buffer.
            4. Driver calls BIO to create a frame for the used buffer.
            5. Frame is created; user callback function is called via the BIO Rx callback.

            NOTE       See Hardware Abstraction Layers (HAL) for information about frames and
                       frame pools.



118                                                                       SmartDSP OS User Guide
Drivers
                                          QUICC Engine Unified Ethernet Controller (QE UEC)


           Programming Model
           This section covers driver bring-up—first by the OS, then by the application-chosen API.
           The API of the UEC driver handles initialization and control command functionality.


           General
           The UEC driver is implemented under the BIO abstraction layer.
               • User calls BIO methods to indirectly activate UEC driver methods.
               • BIO methods recieve UEC parameters; e.g., flags and structures.
               • Parameters are passed to the LLD.

           Table 4.9 details SoC configuration file structures; e.g., msc815x_config.c.
           msc815x_uec_init_params_t includes all the structures noted between the typedef struct
           brackets.
           typedef struct
           {
           uint8_t uec_id;
           uint32_t uec_base;
           uec_if_t uec_if;
           uint32_t config_flags;
           os_hwi_priority irq_priority;
           uint16_t max_tx_bd_ring_len;
           uint16_t max_rx_bd_ring_len;
           uint16_t max_rx_buf_len;
           uint8_t num_tx_bd_rings;
           uint8_t       num_rx_bd_rings;
           uec_num_of_threads_t num_tx_threads;
           uec_num_of_threads_t num_rx_threads;
           bool file_by_mac_address;
           uec_filter_t *filters;
           uec_eth_params_t *eth_params;
           } msc815x_uec_init_params_t;




SmartDSP OS User Guide                                                                         119
Drivers
QUICC Engine Unified Ethernet Controller (QE UEC)


Table 4.9 SoC Configuration File Structures

             Structure                                     Description

             uint8_t uec_id                                UEC device index (zero based).

             uint32_t uec_base                             Base address of UEC memory map.

             uec_if_t uec_if                               Ethernet physical interface type.

             uint32_t config_flags                         UEC configuration flags (UEC_CFG_x).

             os_hwi_priority irq_priority                  IRQ prioritization of UEC interrupts.

             uint16_t max_tx_bd_ring_len                   Maximum Tx BD ring length.

             uint16_t max_rx_bd_ring_len                   Maximum Rx BD ring length.

             uint16_t max_rx_buf_len                         • Maximum buffer length for Rx
                                                               rings; multiple of 128.
                                                             • Same value for all the rings.

             uint8_t num_tx_bd_rings                       Number of Tx BD rings (queues).

             uint8_t num_rx_bd_rings                       Number of Rx BD rings (queues).

             uec_num_of_threads_t num_tx_threads           Number of QE Tx threads.

             uec_num_of_threads_t num_rx_threads           Number of QE Rx threads.

             bool file_by_mac_address                      If FALSE,
                                                             • user is responsible for filing
                                                               frames;
                                                             • done by supplying a filter array
                                                               and patterns.

             uec_filter_t *filters                         Sets to FALSE,
                                                             • a filter array used for pattern
                                                               matching in
                                                               file_by_mac_address.

             uec_eth_params_t *eth_params                    • Pointer to Ethernet
                                                               parameters
                                                             • NULL will use defaults.


            Table 4.10 details a structure defined per UEC channel (BD ring). The structure defines
            main characteristics and configurations.




120                                                                     SmartDSP OS User Guide
Drivers
                                             QUICC Engine Unified Ethernet Controller (QE UEC)

            uec_channel_params_t includes all the structures noted between the typedef struct
            brackets.
            typedef struct
            {
            uint32_t addr_high32;
            uint16_t addr_low16;
            uint16_t bd_ring_len;
            bool interrupt_en;
            uint8_t coherency_en;
            os_mem_type heap;
            uint16_t lossless_flow_control_threshold;
            } uec_channel_params_t;


Table 4.10 UEC Channel (BD ring)-defined Structure

                Structure                              Description

                uint32_t addr_high32                   32-bits (high) of the MAC address channel.

                uint16_t addr_low16                    16-bits (low) of the MAC address channel.

                uint16_t bd_ring_len                   Length of BD ring.

                bool interrupt_en                        • Tx channel: If TRUE, confirm
                                                           transmitted frames upon interrupt.
                                                         • Rx channel: If FALSE, process
                                                           received frames by polling (without
                                                           Rx interrupt).

                uint8_t coherency_en                     • Tx channel: If TRUE, flushes
                                                           frame from cache before transmit.
                                                         • Rx channel: If TRUE, invalidates
                                                           frame before receive (buffers must
                                                           be in system area only).

                os_mem_type heap                       Heap used for channel BDs.

                uint16_t                               LossLess flow control threshold.
                lossless_flow_control_threshold




SmartDSP OS User Guide                                                                             121
Drivers
QUICC Engine Unified Ethernet Controller (QE UEC)

            Table 4.11 details command definitions used to control a UEC device or channel.
            osBioDeviceCtrl() and osBioChannelCtrl() are called, respectively. In some cases,
            additional parameters are required.
Table 4.11 UEC Commands

             Command                                   Description

             UEC_CMD_ENABLE                               • Enables UEC operation. bdsaq

             UEC_CMD_TX_RESTARTBIO_DEVIC                  • Resume Tx operation.
             E_TX_ENABLE                                  • Param: NULL

             UEC_CMD_RX_RESTARTBIO_DEVIC                  • Resume Rx operation.
             E_RX_ENABLE                                  • Param: NULL

             UEC_CMD_TX_STOPBIO_DEVICE_T                  • Stop Tx after current frame.
             X_DISABLE                                    • Param: pointer to
                                                            uec_stop_params_t

             UEC_CMD_RX_STOPBIO_DEVICE_R                  • Stop Rx after current frame.
             X_DISABLE                                    • Param: pointer to
                                                            uec_stop_params_t

             UEC_CMD_ADD_MCAST_ADDRESS                    • Add address to UEC extended
                                                            filtering.
                                                          • Param: ip address

             UEC_CMD_REMOVE_MCAST_ADDR                    • Remove address from UEC
             ESS                                            extended filtering.
                                                          • Param: ip address

             UEC_CMD_TX_ON_DEMAND                         • Cause an immediate Tx when in
                                                            polling mode.
                                                          • Param: NULL

             UEC_CMD_TX_PAUSE                             • Transmit a Pause frame.
                                                          • Param: pointer to
                                                            uec_pause_params_t

             UEC_CMD_TX_RESUME                            • Transmit a flow control "Resume"
                                                            frame.
                                                          • Param: NULL

             UEC_CMD_TX_HDFC_START                        • Start half-duplex flow control for
                                                            Tx.
                                                          • Param: NULL

             UEC_CMD_TX_HDFC_STOP                         • Stop half-duplex flow control for
                                                            Tx.
                                                          • Param: NULL



122                                                                     SmartDSP OS User Guide
Drivers
                                  QUICC Engine Unified Ethernet Controller (QE UEC)

Table 4.11 UEC Commands

            Command                         Description

            UEC_CMD_INT_ENABLE                • Unmask specified interrupts.
                                              • Param: uint32_t combining
                                                UEC_INTR_x values

            UEC_CMD_INT_DISABLE               • Mask specified interrupts.
                                              • Param: uint32_t combining
                                                UEC_INTR_x values

            UEC_CMD_STAT_GET                  • Get statistics data.
                                              • Param: pointer to uec_statistics_t*

            UEC_CMD_STAT_RESET                • Reset statistics counters.
                                              • Param: NULL

            UEC_CMD_ADDITIONAL_TX_STAT_       • Get additional Tx statistics data.
            GET                               • Param: pointer to
                                                uec_additional_tx_statistics_t*

            UEC_CMD_ADDITIONAL_RX_STAT_       • Get additional Tx statistics data.
            GET                               • Param: pointer to
                                                uec_additional_rx_statistics_t*

            UEC_CMD_ENTER_PATTERNS            • Program the pattern matching
                                                mechanism.
                                              • Param: pointer to
                                                uec_filing_params_t

            UEC_CMD_PHY_REG_WRITE             • Write to a PHY register via MII.
                                              • Param: pointer to
                                                uec_phy_access_t

            UEC_CMD_PHY_REG_READ              • Read from a PHY register via MII.
                                              • Param: pointer to
                                                uec_phy_access_t

            UEC_CMD_UTFTT_REG_WRITE           • Modify the UTFTT register value.
                                              • Param: new value

            UEC_CMD_CONFIG_SCHEDULER          • Configure a scheduler queue
                                                scheduling policy.
                                              • Param: pointer to
                                                uec_scheduler_config_params_t

            UEC_CMD_ADD_MAC_ADDRESS           • Add MAC address to UEC.
                                              • Param: pointer to MAC address




SmartDSP OS User Guide                                                                123
Drivers
QUICC Engine Unified Ethernet Controller (QE UEC)

Table 4.11 UEC Commands

             Command                                    Description

             UEC_CMD_REMOVE_MAC_ADDRES                    • Remove MAC address from the
             S                                              UEC.
                                                          • Param: pointer to MAC address

             UEC_CMD_RX_POLL                              • Process received frames when Rx
                                                            interrupt is disabled.
                                                          • Param: NULL

             UEC_CMD_TX_CONFIRM                           • Confirm transmitted frames.
                                                          • Param: NULL

             UEC_CMD_DBG_PRINT_ALLOC_TXB                  • Allocate Tx BD buffers for Debug
             DBUF                                           Print feature.
                                                          • Param: length of Tx BD data
                                                            buffer.

             UEC_CMD_DBG_PRINT_TX_BDINIT                  • Initialize Tx BD buffer for Debug
                                                            Print Tx channel.
                                                          • Param: buffer length, buffer



            Calling Sequence Example
            Table 4.12 lists functions included in the UEC driver API.




124                                                                      SmartDSP OS User Guide
Drivers
                                     QUICC Engine Unified Ethernet Controller (QE UEC)


Table 4.12 QE UEC API

            Flow Stage        Name                        Description

            Kernel Bring-up   osInitialize() ->             • User application
                              osArchDevicesInitialize()       indirectly calls these
                              ->                              functions.
                              qeInitialize()                • osInitialize()
                                                              calls
                                                              qeInitialize();
                                                              os_config.h and
                                                              msc81xx_config.c
                                                              contain
                                                              definitions and
                                                              configuration
                                                              structures.
                                                            • osInitialize()
                                                              initializes the OS and
                                                              calls function
                                                              osArchDevicesIni
                                                              tialize()to
                                                              initialize the
                                                              architecture and all
                                                              application-required
                                                              devices.
                                                            • osArchDevicesInit
                                                              ialize() calls
                                                              qeInitialize()
                                                              to initialize the QE.
                              osInitialize() ->             • osInitialize()
                              osArchDevicesInitialize()       calls
                              ->                              osArchDevicesIni
                                                              tialize() which, in
                              uecInitialize() ->              turn, calls
                              bioRegister()                   uecInitialize();
                                                              latter initializes the
                                                              UEC driver.
                                                            • uecInitialize()
                                                              calls
                                                              bioRegister() to
                                                              take and register the
                                                              driver to the BIO
                                                              abstraction layer.
                                                            • bioRegister()
                                                              returns the BIO
                                                              device handle; LLD
                                                              uses it for BIO calls to
                                                              this device.




SmartDSP OS User Guide                                                                   125
Drivers
QUICC Engine Unified Ethernet Controller (QE UEC)

Table 4.12 QE UEC API (continued)

             Flow Stage           Name                    Description

             Application Bring-   osBioDeviceOpen() ->     • osBioDeviceOpen()
             up                   uecOpen()                  opens a BIO device
                                                             for operation.
                                                           • Uses given
                                                             parameters and
                                                             returns a BIO device
                                                             handle.
                                                           • Calls uecOpen() to
                                                             get a handle to the
                                                             UEC HW.
                                  osBioChannelOpen() ->    • osBioChannelOpen(
                                  uecChannelOpen()           ) opens a BIO
                                                             device channel.
                                                           • Calls
                                                             uecChannelOpen()
                                                             to get a handle to the
                                                             UEC queue.

             Application          osBioChannelTx() ->      • osBioChannelTx()
             Runtime              uecMbfChannelTx() or       transmits a frame via
                                                             a BIO channel
                                  uecSbfChannelTx()          previously opened for
                                                             transmission.
                                                           • Calls
                                                             uecMbfChannelTx(
                                                             ) or
                                                             uecSbfChannelTx(
                                                             ).
                                  osBioDeviceCtrl() ->     • osBioDeviceCtrl()
                                  uecCtrl()                  performs control
                                                             commands on a
                                                             device.
                                                           • Calls uecCtrl().
                                                           • uecCtrl() performs
                                                             a predefined device-
                                                             level control; e.g.,
                                                             adding a filter.
                                  osBioChannelCtrl() ->    • osBioChannelCtrl(
                                  uecChannelCtrl()           ) performs control
                                                             commands on a
                                                             channel and calls
                                                             uecChannelCtrl()
                                                             .
                                                           • uecChannelCtrl()
                                                             performs a predefined
                                                             channel-level control;
                                                             e.g., poll for received
                                                             frames.


126                                                          SmartDSP OS User Guide
Drivers
                                             QUICC Engine Unified Ethernet Controller (QE UEC)

Table 4.12 QE UEC API (continued)

             Flow Stage            Name                          Description
                                   uecMbfTxIsr()                    • Calls an interrupt
                                                                      service routine.
                                                                    • Occurs when a
                                                                      packet—configured to
                                                                      issue an interrupt—
                                                                      has been sent, and
                                                                      the UEC multi-
                                                                      buffered frame
                                                                      mechanism is
                                                                      enabled.
                                   uecSbfTxIsr()                    • Calls an interrupt
                                                                      service routine.
                                                                    • Occurs when a
                                                                      packet—configured to
                                                                      issue an interrupt—
                                                                      has been sent, and
                                                                      the UEC multi-
                                                                      buffered frame
                                                                      mechanism is
                                                                      disabled (default).
                                   uecMbfRxIsr()                    • Calls an interrupt
                                                                      service routine.
                                                                    • Occurs when a
                                                                      packet—configured to
                                                                      issue an interrupt—
                                                                      has been received,
                                                                      and the UEC multi-
                                                                      buffered frame
                                                                      mechanism is
                                                                      enabled.
                                   uecSbfRxIsr()                    • Calls an interrupt
                                                                      service routine.
                                                                    • Occurs when a
                                                                      packet—configured to
                                                                      issue an interrupt—
                                                                      has been received,
                                                                      and the UEC multi-
                                                                      buffered frame
                                                                      mechanism is
                                                                      disabled (default).



           Functionality
           This section details initialization.




SmartDSP OS User Guide                                                                        127
Drivers
QUICC Engine Unified Ethernet Controller (QE UEC)

            Initialization
            QE handles all controller traffic therefore the QE and controllers must be initialized at the
            SoC-level.
            1. QE initialization header file:
               initialization/arch/msc81xx/include/qe_init.h
            2. UEC initialization header file:
               initialization/arch/msc81xx/include/msc81xx_uec_init.h
            3. Enable individual UECs at os_config.h by setting the macros to ON:
               #define MSC81XX_UEC0 ON
               #define MSC81XX_UEC1 ON
            4. Function uecInitialize() is responsible for the following:
              • Initializes UEC based on the msc81xx_config.c structure of
                msc81xx_uec_init_params_n.
              • Calls initEtherPhy(), a BSP callback function for initializing the board. If not
                implemented, a link time error will occur.


            Source Code
            UEC driver header files:
Table 4.13 UEC Header Files

             File Source        Type                Details

             MSC814x            Initialization      smartDSPinitializationarchmsc814xincludemsc
                                                    814x_uec_init.h

                                Runtime             smartDSPincludearchstarcoremsc814xmsc81
                                                    4x_uec.h

             MSC815x            Initialization      smartDSPinitializationarchmsc815xincludemsc
                                                    815x_uec_init.h

                                Runtime             smartDSPincludearchstarcoremsc815xmsc81
                                                    5x_uec.h



            Demo Use Cases
            UEC driver demos:
              • demosstarcoremsc815xnet_demo
              • demosstarcoremsc815xnet6_demo
              • demosstarcoremsc815xnet_ip4_ip6_demo


128                                                                        SmartDSP OS User Guide
Drivers
                                                                              Serial RapidIO (sRIO)

              • demosstarcoremsc815xnet_mbf
              • demosstarcoremsc815xuec_multicore

           NOTE           Additional demos can be found in the SmartDSP release layout.



Serial RapidIO (sRIO)
           Introduction
           Serial RapidIO(R) (sRIO) is a point-to-point, packet-based, switched-system, interconnect
           technology. sRIO provides high performance and bandwidth as well as faster bus speed
           interconnect technology.
           sRIO is an intra-system interface that provides chip-to-chip and board-to-board
           communication at GBps performance levels.It was developed to control data and signal
           plane applications of large-scale embedded systems.
           RIO is characterized by the following:
              • One or two hosts but up to 65,534 agents.
              • Agents can scan and exchange data in the system.
              • RIO agents are connected via RIO switches.
           The RIO standard defines multiple transaction types:
Table 4.14 RIO Transaction Types

             Transaction                 Description                    Module Applications

             Direct I/O                  Writes to destination          Modules can work
                                         memory.                        simultaneously.

             Doorbell                    Short (2 bytes) messages         • Bus: specifies
                                                                            the address
                                         from source to destination.        space going to
                                                                            the SRIO
             Messaging                   Transfers a message (max. 4        interface.
                                         KB) from source to
                                                                          • Packet:
                                         destination.                       exchanges
                                                                            messages
             Maintenance                    • Standard or                   between SRIO
             Accesses                         implementation-               agents.
                                              specific registers
                                              in a destination’s          • Doorbell:
                                              RIO address                   messages
                                              space.                        contain 16-bit
                                                                            information,
                                            • Port-Write: passes            source ID, and
                                              error information.            destination ID.


SmartDSP OS User Guide                                                                           129
Drivers
Serial RapidIO (sRIO)


            Features
            A sRIO driver supports the following RIO transaction types:
Table 4.15 RIO Transaction Types

              Transaction                            Description

              Type5                                  RIO NWRITE

              Type6                                  RIO SWRITE

              Type8                                  RIO Maintenance

              OCeaN DMA                              Direct access

              ATMU Bypass                            MSC814x supports small system maintenance.

              ATMU                                   MSC815x supports small & large system
                                                     maintenance.



            Relevant SoC
            SmartDSP OS sRIO drivers support MSC814x and MSC815x devices; see Table 4.3.
Table 4.16 SoC RIO Support

              Support                             Description

              Direct I/O                            • Supported by OCeaN DMA (in the HW).
                                                    • Programmable via the following:
                                                     – Standard SmartDSP OS DMA API
                                                       channels, chains, and transfers
                                                     – Direct access to OCeaN DMA

              Maintenance                           • Supported by
                                                      demosstarcoremsc815xuart.
                                                     – MSC814x supports small systems
                                                       maintenance using ATMU bypass.
                                                       Maintenance access is generated using
                                                       srioDmaMaintenanceAccess().
                                                     – MSC815x supports maintenance in small
                                                       and large systems using ATMU.



            Architecture
            This section covers the SW architecture of the system sRIO driver.




130                                                                       SmartDSP OS User Guide
Drivers
                                                                           Serial RapidIO (sRIO)

           Components
           This section details sRIO driver components.
Table 4.17 sRIO Driver Components

            Component                            Description

            Controller                              • Represents the HW block.
                                                    • 34-bit address support.
                                                    • I/O ATMU windows.

            SRIO Window                          ATMU window for I/O type 5/6 transactions.

            Maintenance ATMU                     ATMU window for maintenance transactions.

            Port                                 Represents the HW port.



           Data Flow
           This section outlines transaction and maintenance data flows.
           NWRITE and SWRITE transaction flows:
           1. Application pre-configures I/O windows.
           2. Application writes data to the outbound ATMU window address space.
           3. MSC814x OCN DMA transfers:
              a. [Optional} For MSC8157
              b. [Mandatory] For sRIO transaction over MSC8156_FAMILY—executed with the
                 OCN DMA API.
           Maintenance data flow:
           1. Open maintenance ATMU.
           2. Write data via SRIO maintenance access procedure.
           3. Close maintenance ATMU.


           Programming Model
           This section covers driver bring-up—first by the OS, then by the application-chosen API.


           General
           The sRIO driver API has the following functionality:
                   • write transactions


SmartDSP OS User Guide                                                                         131
Drivers
Serial RapidIO (sRIO)

                   • maintenance accesses
                   • sRIO generic
            See the SmartDSP OS API Reference Manual for a complete list of sRIO LLD API.
            Table 4.18 describes the MSC815x driver API in light of driver functionality.

            NOTE        For the MSC814x API, replace the function prefix ocnDMA with srioDMA.

Table 4.18 Functionality Perspective of MSC815x API

              Functionality API        Functions                          Description

              Write Transactions         • srioOutboundWindowO            I/O window
                                           pen                            management.
                                         • srioOutboundWindowFi
                                           nd
                                         • srioOutboundWindowFr
                                           ee
                                         • srioOutboundWindowE
                                           nable
                                         • srioOutboundWindowDi
                                           sable
                                         • srioInboundWindowOp
                                           en
                                         • srioInboundWindowFin
                                           d
                                         • srioInboundWindowFre
                                           e
                                         • srioInboundWindowEn
                                           able
                                         • srioInboundWindowDis
                                           able




132                                                                     SmartDSP OS User Guide
Drivers
                                                                          Serial RapidIO (sRIO)

Table 4.18 Functionality Perspective of MSC815x API

             Functionality API        Functions                        Description

             Maintenance API            • srioMaintenanceAtmuO         Maintenance access
                                          pen                          management.
                                        • srioMaintenanceAtmuF
                                          ree
                                        • srioMaintenanceAcces
                                          s
                                        • srioMaintenanceTarget
                                          Set

             sRIO Generic API           • srioRecover                  sRIO management and
                                        • srioClearPortErrors          controls.

                                        • srioAlternateIdSet
                                        • srioAlternateIdDisable
                                        •
                                            srioAcceptAllConfigur
                                            e
                                        • srioDeviceAdd



            Calling Sequence Example
            Table 4.19 lists functions included in the write transactions API of the SmartDSP OS
            MSC8156_FAMILY sRIO driver. Functions include kernel bring-up, application bring-
            up, application runtime, and application teardown.




SmartDSP OS User Guide                                                                        133
Drivers
Serial RapidIO (sRIO)


Table 4.19 N/SWRITE Transactions API

              State                  Function                 Description

              Kernel Bring-up        osInitialize() ->         • User application
                                     archDeviceInitialize()      indirectly calls
                                     ->                          these functions.
                                     srioInitialize()          • osInitialize() calls
                                                                 oInitialize()— as
                                                                 based on
                                                                 os_config.h defines
                                                                 and
                                                                 msc81xx_config.c
                                                                 configuration
                                                                 structures.
                                                               • Initializes sRIO
                                                                 driver.
                                                               • Opens ATMU I/O
                                                                 windows.
                                                               • Enables I/O
                                                                 windows.
                                                               • Initializes sRIO
                                                                 system on the ADS.

              Application Bring-up   ocnDmaControllerOpen()    • Must be first
                                                                 function called.
                                                               • Returns an OCN
                                                                 DMA controller
                                                                 handle.
                                                               • Handle is a
                                                                 parameter in calling
                                                                 other functions.
                                     ocnDmaChannelOpen         • Opens a pre-
                                                                 allocated channel.
                                                               • Initializes channel
                                                                 structure as per
                                                                 configuration
                                                                 parameters.
                                     ocnDmaChainCreate         • Creates an OCN
                                                                 DMA chain.
                                                               • Initializes chain
                                                                 structure as per
                                                                 configuration
                                                                 parameters.
                                     ocnDmaChainTransferAdd    • Adds a transfer to
                                                                 the OCN DMA
                                                                 chain.




134                                                             SmartDSP OS User Guide
Drivers
                                                                           Serial RapidIO (sRIO)

Table 4.19 N/SWRITE Transactions API

            State                    Function                      Description

            Application Runtime      ocnDmaTransfer                   • Performs a transfer
                                                                        & transaction starts.
                                     ocnDmatransferAdd                • Adds a transfer to a
                                                                        chain.
                                     ocnDmaChannelBind                • Binds a chain to a
                                                                        channel.
                                     ocnDmachannelStart               • Starts transaction.

            Application Teardown     ocnDmaChannelUnbind              • Unbinds chain from
                                                                        a channel.
                                     ocnDmaChannelClose               • Frees OCN DMA
                                                                        channel.


           Table 4.20 lists functions included in the maintenance transactions API of the SmartDSP
           OS MSC8156_FAMILY sRIO driver. The functions include kernel bring-up, application
           bring-up, application runtime, and application teardown.




SmartDSP OS User Guide                                                                          135
Drivers
Serial RapidIO (sRIO)

Table 4.20 MAINTENANCE Transactions API
Table 4.21

              State               Function                         Description

              Kernel Bring-up     osInitialize() ->                   • User application
                                  archDeviceInitialize() ->             indirectly calls these
                                                                        functions.
                                  srioInitialize()
                                                                      • osInitialize() calls
                                                                        oInitialize()— as
                                                                        based on os_config.h
                                                                        defines and
                                                                        msc81xx_config.c
                                                                        configuration
                                                                        structures.
                                                                      • Initializes sRIO driver.
                                                                      • Initializes sRIO
                                                                        system on the ADS

              Application         ocnDmaControllerOpen()              • Must be first function
              Bring-up                                                  called.
                                                                      • Returns an OCN
                                                                        DMA controller
                                                                        handle.
                                                                      • Handle is a parameter
                                                                        in calling other
                                                                        functions.
                                  ocnDmaChannelOpen                   • Opens a pre-
                                                                        allocated channel.
                                                                      • Initializes channel
                                                                        structure as per
                                                                        configuration
                                                                        parameters.
                                  srioMaintenanceAtmuOpen             • Opens ATMU window
                                                                        for RIO maintenance.

              Application         srioMaintenanceAccess               • Executes
              Runtime                                                   maintenance access
                                                                        (W/R).

              Application         srioMaintenanceAtmuClose            • Frees a maintenance
              Teardown                                                  ATMU window.
                                  ocnDmaChannelClose                  • Frees an OCN DMA
                                                                        channel.



             Functionality
             The below description provides information for operating data transactions over sRIO.



136                                                                     SmartDSP OS User Guide
Drivers
                                                                               Serial RapidIO (sRIO)

           Initialization
           Follow these steps to initialize data transaction functionality over the sRIO driver:
           1. Enable sRIO support in the application os_config.h file by setting #define
              MSC81XX_SRIO ON.
           2. Enable OCN DMA support in the application os_config.h file by setting #define
              MSC81XX_OCN_DMAx ON.
           3. Allocate memory—enables driver to handle an OCN DMA channel.
           4. Allocate memory for a OCN DMA chain handle.
           5. User application determines DMA chain parameters.
           6. Get an OCN DMA controller handle using osDmaControllerOpen().
             • Function returns the handle to the driver-allocated OCN DMA controller.
             • User application retrieve this handle to open OCN DMA channels and create OCN
               DMA chains.
           7. Create an OCN DMA chain using ocnDmaChainCreate().
           8. Add DMA transfers to the DMA chain using ocnDmaChainTransferAdd() or
              ocnDmaChainTransferAddEx().
             • ocnDmaChainTransferAddEx() returns a handle to added transfers; this allows
               attribute modification.

           Runtime
           Follow these steps to run sRIO in the application:
           1. Bind the OCN DMA channel with a chain using ocnDmaChannelBind().
           2. Start the OCN DMA transaction using ocnDmaChannelStart().
           3. Poll a channel to check if it is active using ocnDmaChannelIsActive().

           Free
           Follow these steps to free OCN DMA:
           1. Ensure OCN DMA channel is inactive.
           2. Unbind DMA channel and chain using the function, osDmaChannelUnbind().
             • Indicates DMA chain can be deleted or bound to a different DMA channel.
             • Indicates DMA channel can be closed or bound to a different DMA chain.
           3. Release DMA channel using osDmaChannelClose().
             • Releases all DMA channel resources (except memory) belonging to a user
               application.
           4. Release DMA chain using osDmaChainDelete().


SmartDSP OS User Guide                                                                             137
Drivers
Doorbell

             • Releases all OCN DMA channel resources (except memory) belonging to a user
               application.


           Source Code
           SmartDSP OS sRIO driver header files:
             • includearchstarcoremsc815xmsc815x_srio.h
             • initializationarchmsc815xincludemsc815x_srio_init.h
             • includearchstarcoremsc814xmsc814x_srio.h
             • initializationarchmsc814xincludemsc814x_srio_init.h


           Resource Management
           Minimize driver data footprints by assigning OCN DMA channels-to-cores at compilation
           time.
             • Driver configures the master core (osGetMasterCore()) to handle errors during
               srioInitialize() execution.
             • Driver handles HW-related errors.
             • User callback functions handle functional errors.


           Demo Use Cases
           demosstarcoremsc815xrio_dma
           demosstarcoremsc814xrio_dma


Doorbell
           Introduction
           RapidIO (R) type10 traffic, also known as doorbells; is used to pass a short message (2
           bytes) from one endpoint to another. Generally it is used to pass control information.


           Features
           The sRIO doorbell driver has the following features:
             • Enabled by setting it to ‘ON’ in the os_config.h file using
               #define MSC81XX_DOORBELL ON.
             • Generates short messages in which 16 bits are reserved as part of the header.


138                                                                    SmartDSP OS User Guide
Drivers
                                                                                            Doorbell

             • Runs only in the master core.


           Relevant SoC
           MSC8144
           MSC815x


           Architecture
           Design Decisions
           User applications that share Rx doorbells among cores can consider these two approaches:
             • If the 16-bit doorbell information is important to all cores then the channel callback
               function generates and transmits an intercore message.
             • If only knowledge of the doorbell is important (versus the 16-bit information) then
               all cores (aside from the master) call osHwiCreate() and register themselves to
               the doorbell interrupt.

           NOTE       The master core calls CIO functions thus only a single core manages the HW.



           Programming Model
           Calling Sequence Example
           Doorbell API
           The sRIO doorbell driver is a CIO. The architecture-dependant header file of the sRIO
           doorbell driver is includearchstarcoremsc81xxmsc81xx_doorbell.h.
           Table 4.22 lists various sRIO doorbell driver API functions.




SmartDSP OS User Guide                                                                            139
Drivers
Doorbell


Table 4.22 sRIO Doorbell Driver

             Status               Name                          Description

             Kernel Bring-up      osInitialize() ->              • User application
                                  osArchDevicesInitialize() -      does not directly
                                  >                                call these
                                                                   functions.
                                  srioInitialize()
                                                                 • osInitialize()
                                                                   calls
                                                                   srioInitializ
                                                                   e() based on
                                                                   os_config.h
                                                                   defines and
                                                                   msc81xx_confi
                                                                   g.c configuration
                                                                   structures.
                                                                 • Initializes sRIO
                                                                   driver.
                                  osInitialize() ->              • osInitialize()
                                  osArchDevicesInitialize() -      calls
                                  >                                doorbellIniti
                                                                   alize()to start
                                  doorbellInitialize() ->          the doorbell
                                  cioRegister()                    driver.
                                                                 • cioRegister():
                                                                  – registers the driver to
                                                                    the CIO abstraction
                                                                    layer.
                                                                  – returns a pointer to the
                                                                    CIO device handle.
                                                                  – LLD uses the pointer
                                                                    for CIO calls to this
                                                                    device.

             Application Bring-   osCioDeviceOpen() ->           • Must be first
             up                   doorbellOpen()                   function called.
                                                                 • Returns a CIO
                                                                   device handle.
                                  osCioChannelOpen() ->          • Opens a pre-
                                  doorbellChannelOpen()            allocated CIO
                                                                   device channel.
                                                                 • Initializes doorbell
                                                                   channel structure
                                                                   as per
                                                                   configuration
                                                                   parameters.




140                                                              SmartDSP OS User Guide
Drivers
                                                                               PCI Express (PCIe)

Table 4.22 sRIO Doorbell Driver (continued)

             Status                Name                               Description

             Application           osCioChannelTx() ->                  • osCioChannelTx
             Runtime               doorbellChannelTx()                    () transmits a
                                                                          frame via a
                                                                          previously opened
                                                                          CIO channel.
                                                                        • Calls
                                                                          doorbellChann
                                                                          elTx()to send a
                                                                          doorbell
                                                                          message.
                                   osCioDeviceCtrl() ->                 • osCioDeviceCtr
                                   doorbellChannelCtrl()                  l()performs
                                                                          control
                                                                          commands.
                                                                        • doorbellChanne
                                                                          lCtrl()perform
                                                                          s a channel-level
                                                                          controlling
                                                                          function.
                                   doorbellRxIsr()                      • Upon message
                                                                          receipt, generates
                                                                          a receive interrupt
                                                                          service routine.



            Demo Use Cases
            demosstarcoremsc814xdoorbell
            demosstarcoremsc815xemsg_doorbell
            demosstarcoremsc815xdoorbell


PCI Express (PCIe)
            PCIe driver is implemented as part of SmartDSP OS drivers. MSI is an optional feature. A
            system-specified message written to a system-specified address enables a device to
            request service. For example, a PCI DWORD memory write transaction.
            The PCIe MSI driver supports PCIe MSI messages.


            Features
            Features include the following:



SmartDSP OS User Guide                                                                          141
Drivers
PCI Express (PCIe)

              • Supported on MSC815x; connect to PCIe at EP or RC using the function
                pexlsRootComplex().
              • Enable (ON)/Disable (OFF) PCIe driver support using macro MSC81XX_PEX in the
                SmartDSP OS configuration file (os_config.h).
            This section lists MSC815x PCIe MSI driver features:
              • Supports a maximum of eight message generations—each message generates a
                different virtual interrupt on the RC side.
              • EP implementation as per PCIe MSI standard.
              • MSI message sent via two implementations:
                 – HW implementation that uses GCR5 pex_irq_out bit to trigger MSI
                   generation.
            SW implementation that uses an outbound ATMU window to map a translated address to
            the MSI address. A write operation—containing MSI address with appropriate data
            values—to the ATMU window generates an MSI transaction to the remote RC.


            Relevant SoC
            MSC815x


            Architecture
            Components
            The below table details PCIe MSI driver components:


Table 4.23 PCIe MSI Driver Components

             Component                          Description

             pex_msi_ep_init_t                     • Contains initialization parameters for
             msi_init_params                         the pexEpMsiInitialize()
                                                     function.
                                                   • EP initializes all
                                                     pex_msi_ep_init_t.* parameters.




142                                                                    SmartDSP OS User Guide
Drivers
                                                                                PCI Express (PCIe)

Table 4.23 PCIe MSI Driver Components

             Component                            Description

             pex_msi_rc_init_t                      • Contains initialization parameters for
             msi_init_params                          the pexRcMsiInitialize()
                                                      function.
                                                    • RC initializes all
                                                      pex_msi_rc_init_t.* parameters.

             pex_msi_handle_t msi_handle            • Holds all relevant information following
                                                      initialization using functions
                                                      pexEpMsiInitialize() or
                                                      pexRcMsiInitialize().
                                                    • pexEpMsiInitialize() execution
                                                      allocates and updates msi_handle.
                                                    • Thereafter, pass the handle to all PCIe
                                                      MSI API functions.



            Design Decisions
            Design decisions relating to a multi-core environment are noted in the below table.
Table 4.24 Multi-core Environment Design Decisions

             Environment               Feature                      Description

             Multi-core                EP                             • Each core acquires a
             Environment                                                spinlock.
                                                                      • Spinlock is released
                                                                        at the end of an
                                                                        operation.
                                                                      • MSI message is sent.

                                       RC                             • Only the master core
                                                                        performs MSI EP
                                                                        initialization.




SmartDSP OS User Guide                                                                            143
Drivers
PCI Express (PCIe)

Table 4.24 Multi-core Environment Design Decisions

             Environment               Feature                      Description

             HW Limitations            VIGR                            • MSI standard
                                                                         indicates that the EP
                                                                         can modify the
                                                                         number of lower bits
                                                                         defined by the MME
                                                                         field but not message
                                                                         data.
                                                                       • MSC815x VIGR
                                                                         implementation has
                                                                         three VIRQ_NUM_L
                                                                         bits.
                                                                       • SmartDSP OS
                                                                         supports up to 8 (2^3)
                                                                         MSI messages.

                                       Endian Swap                     • MSI HW
                                                                         implementation that
                                                                         uses bit
                                                                         GCR5_PEX_IRQ_OUT
                                                                         triggers an MSI
                                                                         generation that
                                                                         causes MSI data to
                                                                         arrive Endian
                                                                         swapped.
                                                                       • May generate only
                                                                         virtual interrupt 0 as it
                                                                         always write zeros to
                                                                         the VIGR lower bits.



            Data Flow
            Transmit/Dispatch Flow
            On the EP, the pexMsiSend(msg_num) function triggers an MSI generation that asserts
            one RC virtual interrupt.


            Receive/Consume Flow
            During MSI initialization, the RC receive flow has two possible forms:
              • RC subscribes to a set of virtual interrupts and initializes EP message data as per
                existing virtual interrupts.
              • RC handles the virtual interrupt and uses hwi_arg to identify the sent message.




144                                                                      SmartDSP OS User Guide
Drivers
                                                     PCI Express (PCIe)

           Programming Model
           This section describes driver bring-up.




SmartDSP OS User Guide                                             145
Drivers
PCI Express (PCIe)

            General
Table 4.25 PCIe MSI Driver Functions

             Feature         Functions                       Description

             RC              os_status pexRcMsiInitialize     • Activate on RC.
                               • pci_dev_t *pci_dev           • Creates virtual
                                                                interrupts.
                               • pex_msi_init_t
                                 *msi_params                  • Initializes all EP MSI
                                                                fields then sets the
                               • pex_msi_handle_t               MSI Message Control
                                 *msi_handle                    Register (0x72) MSIE
                                                                bit to ON.
                                                              • Parameter
                                                                pci_dev_t
                                                                *pci_dev
                                                                represents the EP
                                                                device.

             EP              Tos_status pexEpMsiInitialize    • Activate on EP.
                               • pex_msi_ep_init_t            • Initializes
                                 *msi_params                    msi_handle.
                               • pex_msi_handle_t             • Polls MSI Message
                                 *msi_handle                    Control Register
                                                                (0x72) MSIE bit.

             MSI             os_status pexMsiSend             • Sends MSI message
                                                                using function
                               • void * msi_handle,             pexMsiSwSend() or
                                 uint8_t msg_num                pexMsiHwSend().
                                                              • Function pointer,
                                                                passed to the driver
                                                                during initialization,
                                                                selects the function.

             MSI             os_status pexMsiSendFuncSet      • Replaces send MSI
                                                                function with a new
                               • void * msi_handle,             one. Ensure that the
                               • pex_msi_send_function          initialization
                                                                parameters allow use
                                  send_func
                                                                of both versions.
                                                              • Necessary to set
                                                                OCN DMA
                                                                parameters to use
                                                                pexMsiSwSend()
                                                                function.




146                                                             SmartDSP OS User Guide
Drivers
                                                                               PCI Express (PCIe)

Table 4.25 PCIe MSI Driver Functions

              Feature             Functions                         Description

              MSI                 os_status pexMsiSwSend              • Sends MSI message
                                                                        using a SW
                                    • void * msi_handle                 implementation.
                                    • uint8_t msg_num                 • Generate write
                                                                        transaction using
                                                                        OCN DMA and PCIe
                                                                        Outbound window.
                                                                      • Do not use this
                                                                        function directly.
                                                                        Instead, activate it by
                                                                        using the
                                                                        pexMsiSend()
                                                                        function.

              MSI                 os_status pexMsiHwSend              • Sends MSI message
                                                                        using PEX_IRQ_OUT
                                    • void * msi_handle                 in GCR5.
                                    • uint8_t msg_num                 • EP initiates the
                                                                        transaction using
                                                                        GCR5 thus OCN
                                                                        DMA initialization
                                                                        parameters are not
                                                                        required.
                                                                      • Activate function
                                                                        indirectly using
                                                                        pexMsiSend().



             Calling Sequence Example
             The table below lists RC and EP PCIe MSI driver functions. See General for function
             descriptions, excepting msiHwiIsr().
Table 4.26

              Feature            Function                          Description

              RC                 pexRcMsiInitialize()                • RC is interrupted.
                                                                     • Dispatcher calls
                                                                       cmsiHwiIsr() for
                                                                       each incoming MSI.

              EP                 pexEpMsiInitialize()                • Calls
                                                                       pexMsiSend()when
                                                                       an MSI should be
                                                                       sent to the RC.
                                                                     • Sends messages to
                                                                       the RC.



SmartDSP OS User Guide                                                                             147
Drivers
PCI Express (PCIe)

             The user supplier ISR routine function, msiHwiIsr(), is activated when a virtual interrupt
             is asserted. Use the routine to check the message number and determine further actions.


             Functionality
             This section deals with EP and RC initialization and runtimes.

             EP Initialization
             Listing 4.1 shows EP initialization parameters and their specifications. Listing comments
             denote the following:
                • pexMsiHwSend() function usage might not initialize OCN DMA parameters.
                • If so, set msi_init_params.ocn_dma field to NULL.
                • Specifying these parameters does not effect runtime as they are not used in
                  pexMsiHwSend().

Listing 4.1 EP Initialization

/* For msi_handle allocation */
msi_init_params.heap = OS_MEM_LOCAL_NONCACHEABLE;
msi_init_params.msi_send_func = pexMsiSwSend;
/* Pex Outbound window base for pexMsiSwSend.
 * Outbound window is opened and closed by EP during the pexMsiSwSend*/
msi_init_params.out_win_base = (uint64_t)OUTBOUND_EP_BASE;
/* OCN DMA parameters for windows opening,
 * if only pexMsiSendGCR5 function is used then ocn_dma should be NULL
 * and then there is no need to initialize any OCN DMA parameters */
 msi_init_params.ocn_dma = ocn_dma;
 msi_init_params.dma_channel = dma_channel;
 msi_init_params.ocn_device_id = OCN_DMA_ID0;


             RC Initialization
             Listing 4.2 shows RC initialization parameters and their specifications. Listing comments
             denote the following:
                • Must always initialize all msi_init_params.*parameters.
                • msi_init_params.msi_mme field can get zero to three (0 to 3) values.
                • If msi_init_params.msi_mme = 0 then EP is unable to change message data;
                  thereafter, all EP messages are sent as zero.

Listing 4.2 RC Initialization

/* For msi_handle allocation */


148                                                                       SmartDSP OS User Guide
Drivers
                                                                             PCI Express (PCIe)

msi_init_params.heap = OS_MEM_LOCAL_NONCACHEABLE;
/* Msi message address */
msi_init_params.msi_addr = MSI_BUS_ADDR;
/* Priority for virtual interrupts */
msi_init_params.hwi_priority = OS_HWI_PRIORITY0;
/* Enable 2^mme messages/interrupts */
msi_init_params.msi_mme      = 0x3;
/* Interrupt service routine */
msi_init_params.hwi_handler = msiHwiIsr;
// VIGR = 0xFFF27000
/* RC should route the inbound window to the VIGR vector */
msi_init_params.in_win_translation = (uint64_t)&g_msc815x_ccsr-
>gic.vigr;


           EP Runtime
           1. Activates pexMsiSend(msg_num) in order to send messages.
           2. If the RC allows only a single message (msi_mme = 0) then all msg_num are sent
              as zero.
           3. If the RC allows more then one message during initialization, then the msg_num must
              be smaller than the maximum number of allowed messages.
           4. If required, switch to another type of pexMsiSend() function using
              pexMsiSendFuncSet().

           RC Runtime
           1. Handles received interrupts.
           2. Message numbers are received via the hwi_arg parameter.


           Resource Management
           The master core handles general PCIe interrupts:
             • Clears interrupts. See Interrupts for further information.
             • Activates user callback function.
           See demosstarcoremsc815xuart for PCIe traffic generation information.


           Demo Use Cases
           demosstarcoremsc815xpex_digital_loopback
           demosstarcoremsc815xpex_ep_msi
           demosstarcoremsc815xpex_rc_msi



SmartDSP OS User Guide                                                                       149
Drivers
Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)


Multi Accelerator Platform Engine–
Baseband (MAPLE–B/B2)
            Introduction
            MAPLE-B is a baseband, algorithm accelerator for Turbo, Viterbi, FFT/iFFT, DFT/iDFT,
            and CRC algorithms. MAPLE-B is a PSIF—a programmable controller with CRC
            accelerator and DMA capabilities.
            MAPLE-B2 is a multi-standard, baseband, algorithm accelerator for Channel Decoding/
            Encoding, Fourier Transforms, UMTS chip-rate processing, OFDMA and SC-FDMA
            equalization, and CRC algorithms. MAPLE-B2 is a second generation PSIF (PSIF2)—a
            programmable controller with DMA capabilities.


            Features
            Features of the MSBA8100 and MSC815x family of MAPLE–B/B2 drivers are noted
            below.
              • Implemented as part of the SmartDSP OS drivers.
              • Complies with SmartDSP OS driver rules and API.
              • COP features:
                – Each processing element functions as a COP device.
                – MAPLE also acts as a COP device
                – Belongs to the COP LLD layer that manages jobs and queues.
              • Allows multiple hosts to share a single MAPLE–B/B2 device OR a single host to use
                multiple MAPLE–B/B2 devices.
                – Driver must identify the master host controlling the MAPLE–B/B2.
                – Each MAPLE must have a single master—more than one will cause an error.


            MAPLE–B/B2 goals:
                – Minimum overhead.
                – Seamless integratation of SoC bring-up code.
                – Support MSBA8100 and MSC815x family.
                – User will choose the configuration interface.
                – User dispatches multiple BDs in a single function call.




150                                                                   SmartDSP OS User Guide
Drivers
                                 Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)

           Relevant SoC
           MSBA8100 and MSC815x family.


           Architecture
           This section covers the SW architecture of MAPLE–B/B2 drivers.


           Components
           This section details MAPLE–B/B2 driver components found in the SmartDSP OS. See
           Table 4.27 for further details.
Table 4.27 Maple–B/B2 Components

            Components                           Description

            COP Abstraction Layer                COP module layer; see COP Module.

            Maple LLD                            Functions are activated via COP abstraction layer
                                                 functions.

            Device                                  • Processing element abstraction.
                                                    • All relevant registers and parameters of
                                                      a specific processing element are
                                                      handled as follows:
                                                     – unified under the device concept ; and,
                                                     – initialized when opening the device.

            Channel                                 • BD ring abstraction.
                                                    • A channel, at any given time, can only
                                                      contain a limited number of jobs:
                                                     – each reaped job is removed from the
                                                       channel; and,
                                                     – ensures space for newly dispatched jobs.

            Job                                     • BD abstraction.
                                                    • Similar structure to the HW BD.



           Design Decisions
           Design decisions, along with their reasoning, are noted below.
           3. Restricted channel usage—two different cores cannot open the same channel.
              • Driver was written to minimize runtime overhead.
              • Minimum mutual-exclusion locks.



SmartDSP OS User Guide                                                                            151
Drivers
Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)

            4. Device-sharing—first core to open the device initializes all the registers and
               parameters; other cores will use the existing LLD device handle.
               • Support multicore usage of MAPLE–B/B2.
               • Support multicore usage of all processing elements.
            5. During the MAPLE open device routine, each core subscribes to all MAPLE error
               interrupts.
               • Provide error handling and failure recovery mechanism.
            6. Each channel can handle a limited (user-defined) number of jobs.
               • Allows driver to maintain the channel (for the user).
               • Allows driver to maintain the BD ring DRAM (for the user).


            Data Flow
            This section outlines the dispatch flow.


            Dispatch Flow
            Jobs are dispatched to the PE following correct channel initialization. Listing 4.3 outlines
            a structure for a NULL-terminated, linked, COP job dispatch list. The application, with a
            single function call, can dispatch multiple jobs to each PE.

Listing 4.3 COP Job Dispatching

typedef void* cop_job_id;
 typedef struct cop_job_handle_s
 {
cop_job_id job_id;
/**< Used by the application to identify finished jobs. */
void *device_specific;
/**< LLD specific parameters */
struct cop_job_handle_s* next;
/**< next job */
 } cop_job_handle;

            The job dispatch process (see Figure 4.3) is outlined in the following steps:
            1. User application handles the following:
               a. Prepares a job array (may be a single element).
               b. Calls osCopChannelDispatch(jobs)to send a channel to enqueue jobs.
               c. Passes the array and element(s) to osCopChannelDispatch().



152                                                                       SmartDSP OS User Guide
Drivers
                                 Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)


           NOTE       Use jobs from the memory pool; do not allocate stack jobs. A job pointer is
                      returned after reaping.

           2. COP layer handles the following:
              a. Queues all job pointers, taken from the application layer, into the confirmation job
                 queue of the local memory.
              b. Uses lldChanelDispatch(jobs)to dispatch/add jobs to the MAPLE–B/B2
                 memory BD ring.
              c. Passes the array to the LLD at job completion.
           3. LLD handles the following:
              a. Prepares BD(s).
              b. Initiates a callback function. copChannelDispatchCb(job,status)is
                 used to send BD(s) from MAPLE-B/B2 to local memory.
              c. Copies the Job ID into the BD Task ID field. LLD job description tries to match the
                 BD to allow for a simple sanity check and easy BD preparation.

           NOTE       During release, sanity checks are not asserted in order to save runtime code.

           4. COP calls a user-defined callback function; see Figure 4.3.




SmartDSP OS User Guide                                                                           153
Drivers
Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)

Figure 4.3 MSBA8100 COP Job Description Procedure




            NOTE      Data cache coherency is unsupported as neither COP nor LLD manage data.



            Consume (Reap) Flow
            Job reaping is performed under the following circumstances:
              • Triggered interrupt is enabled.
              • Interrupt is disabled following job dispatch.
              • Channel control function is called during runtime.
            Job reaping process covers the following:
              • LLD iterates over a BD ring.


154                                                                   SmartDSP OS User Guide
Drivers
                                   Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)

              • LLD calls the COP callback function with the BD status—for each BD.
              • COP dequeues a job pointer and calls a user callback function. Before dispatching
                the job, the user application should have data ready in the MAPLE–B/B2 accessible
                memory:
                 – MSBA8100: M2, DDR
                 – MSC815x : M2, M3, DDR0, DDR1


            Programming Model
            This section covers driver bring-up—first by the OS, then by the application-chosen API.


            General
            The MAPLE driver is part of the COP abstraction layer; all driver functions are activated
            via COP-layer functions.
            Bring-up initialization is based on initialization structures defined in
            msc81xx_config.c.
Table 4.28 Driver Functions

             Function                                Description
             osCopDeviceOpen()                       Opens a MAPLE or XxPE device.

             osCopChannelOpen()                      Opens a channel for an XxPE device.

             osCopChannelCtrl()                      Manipulates an XxPE channel.

             osCopDeviceCtrl()                       Manipulates an XxPE device.

             osCopChannelDispatch()                  Dispatches a job list to a channel.

             osInitialize()                          SmartDSP OS initialization using structures
                                                     defined in msc81xx_config.c




SmartDSP OS User Guide                                                                             155
Drivers
Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)

             Calling Sequence Example
Table 4.29 MAPLE–B/B2 Driver API
Table 4.30

             Status             Name                          Description

             Kernel Bring-up    osInitialize()->               • User application
                                osArchDevicesInitialize()->      indirectly calls
                                                                 these functions.
                                mapleInitialize()->
                                                               • osInitialize()
                                copRegister()                    calls
                                                                 mapleInitiali
                                                                 ze()based on
                                                                 os_config.h
                                                                 defines and
                                                                 msc81xx_confi
                                                                 g.c configuration
                                                                 structures.
                                                               • Initializes MAPLE
                                                                 driver.
                                                               • copRegister()
                                                                 takes and
                                                                 registers the driver
                                                                 in the COP LLD
                                                                 layer.
                                osInitialize()->               • mapleXxpeInitia
                                osArchDevicesInitialize()->      lize() initializes
                                                                 MAPLE XXPE.
                                mapleXxpeInitialize()->
                                                               • mapleXxpeInitia
                                copRegister()
                                                                 lize()calls
                                                                 copRegister()
                                                                 .




156                                                            SmartDSP OS User Guide
Drivers
                                  Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)

Table 4.30

             Status                Name                        Description

             Application Bring-    osCopDeviceOpen()->           • Using given
             up                    mapleOpen()->                   parameters,
                                                                   osCopDeviceOp
                                   maple_init()                    en() opens a
                                                                   COP device for
                                                                   operation; it
                                                                   returns a device
                                                                   handle or NULL.
                                                                 • mapleOpen()open
                                                                   s a MAPLE–B/B2
                                                                   channel and
                                                                   returns channel
                                                                   handle.
                                                                 • maple_init()ini
                                                                   tializes the
                                                                   MAPLE–B/B2
                                                                   controller.
                                   osCopDeviceOpen()->           • Using given
                                   mapleXxpeOpen()                 parameters,
                                                                   osCopDeviceOp
                                                                   en() opens a
                                                                   COP device for
                                                                   operation; it
                                                                   returns a device
                                                                   handle or NULL.
                                                                 • mapleXxpeOpen()
                                                                   opens all
                                                                   supported PEs.
                                   osCopChannelOpen()->          • Using given
                                   mapleXxpeChannelOpen()          parameters,
                                                                   osCopDeviceOp
                                                                   en() opens a
                                                                   COP device for
                                                                   operation; it
                                                                   returns a device
                                                                   handle or NULL.
                                                                 • mapleXxpeChanne
                                                                   lOpen()opens a
                                                                   MAPLE PE
                                                                   channel.




SmartDSP OS User Guide                                                                157
Drivers
Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)

Table 4.30

              Status                Name                              Description

              Application           osCopChannelDispatch()->            • osCopChannelDis
              Runtime               mapleXxpeChannelDispatch()            patch() sends a
                                                                          job to a channel
                                                                          previously opened
                                                                          for transmission.
                                                                        • mapleXxpeChanne
                                                                          lDispatch()
                                                                          sends a message.
                                    osCopDeviceCtrl()->                 • osCopDeviceCtrl
                                    mapleDeviceCtrl()                     ()performs
                                                                          control commands
                                                                          on a device.
                                                                        • mapleDeviceCtrl
                                                                          () performs a
                                                                          device-level
                                                                          controlling
                                                                          function.
                                    osCopChannelCtrl()->                • osCopChannelCtr
                                    mapleXxpeChannelCtrl()                l()performs
                                                                          control commands
                                                                          on a channel.
                                                                        • mapleXxpeChann
                                                                          elCtrl()perfo
                                                                          rms a channel
                                                                          control-level
                                                                          function.
                                    mapleXxpeIsr()->                    • Invokes an
                                    mapleXxpeChannelReap()->              interrupt
                                                                          service
                                    copChannelDispatchCb()                routine when
                                                                          the PE
                                                                          triggers an
                                                                          interrupt.
                                                                        • While polling
                                                                          a channel for
                                                                          finished
                                                                          jobs, the reap
                                                                          process can be
                                                                          activated
                                                                          indirectly
                                                                          using
                                                                          osCopChannelC
                                                                          trl().



             Functionality
             The following section covers HW semaphores, initialization processes and runtime.


158                                                                    SmartDSP OS User Guide
Drivers
                                     Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)

            HW Semaphores
            MAPLE HW configuration allows for HW semaphores if they are located on the MAPLE-
            instantiated device.
              • Semaphores synchronize usage when several entities, including MAPLE, generate
                sRIO doorbells in the system. Applicable for MSC815x, but not MSBA8100.
              • Synchronize access to shared resources when devices share the same MAPLE; see
                MAPLE Resource Sharing.

            NOTE       SmartDSP OS doorbell driver does not support HW semaphores.


            Configuration File
            SmartDSP OS configuration file, os_config.h, enables MAPLE-B/B2 and PE by
            setting the below noted MAPLE and MAPLE_XXPE flags to ON.
            For example,
              • #define MAPLE            ON
              • #define MAPLE_TVPE              ON
              • #define MAPLE_FFTPE ON
              • #define MAPLE_DFTPE ON
              • #define MAPLE_CRCPE ON

            NOTE       MSBA8100 does not support #define MAPLE_CRCPE ON.


            Initialization Processes
            Table 4.31 outlines the three initialization processes.
Table 4.31 MAPLE–B/B2 Initialization Processes

             Process                                 Description

             Driver Initialization                     • Initializes MAPLE-B/B2.
                                                       • Enables a PE-specific driver at
                                                         compilation time.




SmartDSP OS User Guide                                                                        159
Drivers
Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)

Table 4.31 MAPLE–B/B2 Initialization Processes

             Process                                Description

             PE Initialization                         • Specifically LLD (MAPLE and all XxPE).
                                                       • Opens the device via the COP
                                                         interface.
                                                       • Returns a device handle.

             Channel Initialization                    • Opens a MAPLE-B/B2 channel via the
                                                         COP interface.
                                                        – Achieved using the device handle returned
                                                          by PE initialization.
                                                       • Returns a channel handle.
                                                       • One-to-one relationship exists between
                                                         a channel and a BD ring.
                                                        – Every MAPLE-B/B2 PE supports up to eight
                                                          high- and low-priority channels.
                                                       • COP channels are not statically
                                                         assigned to cores.
                                                        – Cores open channels by specifying a
                                                          required channel number.
                                                        – Every core opens at least one channel to
                                                          dispatch jobs.
                                                        – A channel, opened by a given core, cannot
                                                          be opened by another core.


            Table 4.32 details driver, PE, and channel initializations. Bring-up initialization is based
            on the initialization structures defined in msc81xx_config.c.




160                                                                        SmartDSP OS User Guide
Drivers
                                    Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)


Table 4.32 MAPLE Initialization Processes

             Driver Initialization              PE Initialization             Channel
                                                                              Initialization

             1. Initialize using functions      1. Initialize MAPLE–B/B2.     1. User application
                osInitialize() or                                                calls
                runtime                         2. Call                          osCopChannelOp
                osCopDeviceOpen().                 osCopDeviceOpen()             en().
                                                   to open a COP
                – Configures MAPLE–B/
                  B2, DSP, and                     device.                    2. User application is
                  (optionally) MMU.                                              provided with
                                                3. Initialize PE.                specific information:
                – Uploads µcode image
                  based on a selected                                            – channel number
                  standard: 3GLTE,              4. User application
                  3GPP, 3GPP2, WiMAX,              provides                      – channel priority
                  or 3GPP2HS.                      MAPLE–B/B2                    – interrupt line (if
                – Divided into specific            instantiation (to which         applicable)
                  initializations:                 the PE belongs).              – number of BDs
                  SmartDSP OS or                                                   in the ring
                  MAPLE–B/B2.                   5. User application
                                                                              3. Initialize COP and
             2. Access MAPLE–B/B2 with             provides PE
                                                                                 LLD channels.
                MAPLE_IN_PLATFORM                  configuration:
                                                                                 – COP channel
                value                               – MAPLE–B/B2 master            initialization
                smartdsp_os_device.h                  configures PE.               structure
                – Set to OFF: To access             – First core to call           contains a
                  MAPLE, user provides                function                     pointer to the
                                                      osCopDeviceOpen              LLD channel
                  callback functions with a
                  32-bit access resolution.           () configures the PE.        initialization
                                                    – MAPLE–B/B2 driver            structure.
                – Set to ON: User
                                                      provides device-to-
                  provides callback                                           4. LLD uses MAPLE–
                  functions; if none are              core synchronization
                                                      mechanisms.                B/B2 DRAM to
                  provided then driver
                                                                                 synchronize the
                  reverts to internal
                  functions.                                                     following: memory,
                – If the driver is unfamiliar                                    interrupts, and BD
                  with the interface used                                        ring assignments of
                  to access MAPLE–B/B2,                                          multiple devices
                  then user application                                          sharing MAPLE–B/
                  must provide a callback
                  function to control R/W                                        B2.
                  access.                                                        – Multiple
                – If the driver does not                                           channels—on
                  perform data access,                                             the same core—
                  then user application                                            can share the
                  does not need to                                                 same MAPLE–
                  provide a callback                                               B/B2 interrupt
                  function.                                                        line.




SmartDSP OS User Guide                                                                              161
Drivers
Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)

            Listing 4.4 is a code snippet used to access MAPLE–B/B2 memory space in a platform-
            independent manner.

Listing 4.4 Function for Accessing MAPLE-B/B2 Memory Space

typedef long (*maple_config_func)(
                                                  void *addr,
                                                  void *data,
                                                  unsigned long int num_bytes,
                                                  unsigned long int dev_id,
                                                  unsigned long int param
                           );
/**< MUST provide big-endian accesses towards MAPLE */


            MAPLE-B/B2 Runtime
            The MAPLE–B/B2 driver does not handle data processed by the MAPLE-B/B2. User
            applications must ensure that all required data is in place before dispatching a job(s) using
            the MAPLE–B/B2 driver.
            The COP job list consists of a NULL-terminated, linked, structure list. Each structure
            points to the LLD job description.
            The following functions detail MAPLE–B/B2 driver runtime:
            1. Dispatch a job to a channel and send BD(s) to the PE channel using
               osCopChannelDispatch().
            2. Returns OS_SUCCESS or an error code from os_error.h.
               The function takes the following arguments:
                 – Channel handle as returned from osCopChannelOpen().
                 – Pointer to a job array.
                 – Number of jobs for dispatch.
            3. osCopDeviceCtrl()controls COP devices using the following commands:
              • MAPLE_CMD_SEMAPHORE_GET
                 – Retrieves semaphore used for sharing the MAPLE-B/B2 driver.
              • MAPLE_CMD_SEMAPHORE_RELEASE
                 – Releases semaphore used for sharing the MAPLE-B/B2 driver.
              • MAPLE_CMD_MALLOC
                 – Allocates memory from the MAPLE-B/B2 DRAM.
              • MAPLE_TVPE_CMD_SET_VITERBI_POLY
                 – Sets viterbi polynomial sets (MTVPVSxCyP).



162                                                                        SmartDSP OS User Guide
Drivers
                                Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2)

               – Set BD VIT_SET field.
               – Select between sets using enumeration, maple_tvpe_vit_set_t.
             • MAPLE_TVPE_CMD_LOAD_INTERLEAVER
               – Used for 3GPP2HS EVDO.
               – Sets (MP_MBUS + 0x464) = &maple_tvpe_interleaver[0].
               – Execute after the maple_init function but before BD activation.

           NOTE       EVDO is not supported on all MAPLE platforms. See the Core Reference
                      Manual for further information.

           4. osCopChannelCtrl()controls COP channels using the following commands.
             • MAPLE_FTPE_CMD_RX_POLL
               – Polls xFTPE channel and BD ring for completed jobs.
             • MAPLE_TVPE_CMD_RX_POLL
               – Polls TVPE channel and BD ring for completed jobs.
             • MAPLE_CRCPE_CMD_RX_POLL
               – Polls CRCPE channel and BD ring for completed jobs.
             • No MAPLE-B/B2 channel commands.


           Source Code
           The MAPLE SmartDSP OS driver can be used as is with inclusion of the Driver
           Initialization and Runtime header files.
           The other files—µcode Initialization API, µcode header file, and MAPLE Driver memory
           map—are included in the driver initialization and runtime files.
Table 4.33 Source Codes

            Source            Type                             Detail

            Library           Driver                           “SmartDSPlibmsc815x*_drive
                                                               rs.elb”

                              Kernel                           “SmartDSPlibmsc815x*.elb”

                              MAPLE µcode                      "SmartDSPlibmaple*.elb"




SmartDSP OS User Guide                                                                        163
Drivers
RIONET

Table 4.33 Source Codes

            Source            Type                                Detail

            Files             Driver Initialization Header File   "SmartDSPinitializationarchpe
                                                                  ripheralsmapleinclude*.h"

                              Driver Runtime Header File          “SmartDSPdriversmaplerev1i
                                                                  nclude*.h”

                              µcode Initialization API            "SmartDSPinitializationarchpe
                                                                  ripheralsmaplemaple_apimsc
                                                                  81XXincludemaple_api.h"

                              µcode Header File                   "SmartDSPinitializationarchpe
                                                                  ripheralsmaplemaple_apimsc
                                                                  81XXrevXinclude*"

                              MAPLE Driver Memory Map             “SmartDSPincludearchperiph
                                                                  eralsmaplerevX*”



           Demo Use Cases
           MAPLE–B/B2 driver demos:
           “SmartDSPdemosstarcoremsc815xmaple_*”
           “SmartDSPdemosstarcoremsc815xmapleb2_*”
           “SmartDSPdemosstarcoremsc814xmaple_*”


RIONET
           RIONET supports messaging between source and destination and allows the tunneling of
           TCP/IP over RapidIO.


           Features
           RIONET features are noted below:
             • BIO-based and, as such, can plug into the network stack.
             • Allows the tunneling of TCP/IP over RapidIO.
             • Uses interrupt/polling to process frames received from QE.
             • RIONET QE μ code is only used for Rx.
             • RIONET LLD:


164                                                                   SmartDSP OS User Guide
Drivers
                                                                                           RIONET

                   – On Tx, adds LLD-specific header to a message.
                   – QE uses added information to route messages to the proper BIO channel on Rx.
                   – Manages queues and spinlocking for Tx.


              Relevant SoC
              Relevant SoCs are those that include the RMU (i.e., MSC814x and MSC8156 and their
              derivatives).


              Architecture
              This section covers the SW architecture of the RIONET driver.


              Driver Components
            This section details RIONET driver components. See Table 4.27 for further details.
Table 4.34 RIONET Driver Components
Table 4.35

               Components                          Description

               BIO Abstraction Layer                  • BIO module layer.
                                                      • See Chapter 2, BIO Module.

               Channel                                • For Rx: de-multiplexed messages from
                                                        mailbox based on RIONET headers.
                                                      • For Tx: QE transmission queue.

               Device                                 • Abstraction to an RMU mailbox.
                                                      • Loads μ code during opening.

               OS Frame                               • Message to send.

               OS Frame Buffer                        • Message data to send.

               RIONET LLD                             • Functions are activated via BIO
                                                        abstraction layer functions.


              Figure 4.4 shows how RIONET manages queues and handles interrupts.




SmartDSP OS User Guide                                                                           165
Drivers
RIONET

Figure 4.4 RIONET Usage for Queue Management and Interrupt Handling




           Data Flow
           RIONET uses a message-passing programming model for inter-processor and inter-device
           communication. The model allows messages to be sent across the interconnect fabric to
           the message HW of a consumer mailbox.


           Transmit Flow
           There is one transmit queue per mailbox and no μ code support. Each SoC core obtains
           (and releases) the Tx spinlock and transmits via that single queue.
           User application follows these steps for a BIO Tx call:
           1. Enqueues a frame on the frame queue.
           2. Obtains a spinlock in order to take control of the shared Tx queue.
           3. Places frame buffer(s) on the LLD BD(s).
           4. Triggers the LLD transmission.
           5. Frees the spinlock.
           6. Receives a number of previously transmitted BDs (if no LLD Tx interrupts) and
              handles them as follows:
              a. Dequeues the frame from the frame queue.
              b. Calls the OS BIO Tx callback function with the frame.


166                                                                    SmartDSP OS User Guide
Drivers
                                                                                          RIONET


           NOTE       RIONET Tx has LLD MMU and cache support.



           Receive Flow
           RIONET supports interrupt and/or Rx polling indications.
             • MSC814x DSP uses virtual interrupts only.
             • MSC815x DSP uses virtual interrupts and direct interrupt lines (from QE to core).
           There are n (application configurable) number of separate Rx queues for a mailbox.
             • Each core opens its Rx channel(s); all must be open before RIONET is enabled.
             • Each Rx channel has the following:
                – A unique identifier (comprising the RIONET application or LLD header) for
                  receiving frames.
                – One Rx queue that accepts frames sent to the designated identifier.
             • QE µcode copies incoming data to prevent overwriting on the HW cyclic buffers.
           Rx flow steps:
           1. For an open LLD channel, the user application takes these steps for each Rx BD in the
              BD ring:
              a. Takes the buffer from the BIO buffer pool.
              b. Enqueues the buffer on the BIO buffer queue.
              c. Places the buffer on the LLD BD.
           2. Upon execution of LLD Rx ISR—by polling or interrupt—the user application handles
              ready BDs (in the BD ring) as follows:
                – Replaces a current buffer (on LLD BD) with a new one from the buffer pool.
                – Prevents LLD underrun by reusing the current buffer (if another buffer is
                  unavailable).
                – Looks for buffer errors; if found in the LLD BD then the HW registers the buffer
                  in the BD and logs it in BIO.
           3. If there are no errors, the user application follows these steps:
              a. Dequeues the buffer from the BIO buffer queue.
              b. Takes a frame (equivalent to buffer handle) from the BIO frame pool.
              c. Constructs a frame from the buffer.
              d. Calls the BIO Rx callback function.




SmartDSP OS User Guide                                                                          167
Drivers
RIONET


          NOTE       RIONET Rx has LLD MMU and cache support.

                     For frame/frame pool information, see Hardware Abstraction Layers (HAL).



          Programming Model
          This section covers driver bring-up—first by the OS, then by the application-chosen API.


          General
          MSC814x and MSC815x RMUs each have 2 mailboxes; however, they do not store
          message header information in their memory. During enqueueing, only the HW holds
          message information. This can lead to the following issues:
            • Introduces queue management problems—identifying which core will handle a
              message based on a letter ID.
            • Introduces interrupt management problems—interrupt handling.
          QE solves and prevents these problems as follows:
            • QE μ code package, included in RIONET, is triggered by sRIO controller interrupts
              that are wired by the SoC to the QE.
            • QE (not BIO channel cores) manages RIONET queues.
            • QE (not the sRIO controller) manages sRIO messaging queues.
            • Each mailbox has its own queue:
               – QE (not the HW) manages queues.
               – QE (not RIONET channel cores) manages queues.
            • QE interrupts the cores:
               – VIRQ and/or dedicated interrupt lines are used for incoming messages.
               – QE copies incoming messages—from the sRIO inbound queues mailbox—to
                 each core destination.


          Calling Sequence Example
          Table 4.36 describes functions included in the architecture-independent API of the
          SmartDSP OS RIONET driver.
          Functions include kernel bring-up, application bring-up, application runtime, and
          application teardown.




168                                                                   SmartDSP OS User Guide
Drivers
                                                                                     RIONET


Table 4.36 Architecture-Independent RIONET API

             Status            Name                          Description

             Kernel Bring-up   osInitialize() ->              • User application
                               osArchDevicesInitialize() -      indirectly calls these
                               >                                functions.
                               qeInitialize()                 • osInitialize()
                                                                calls
                                                                osArchDevicesIni
                                                                tialize() based on
                                                                os_config.h defines
                                                                and
                                                                msc81xx_config.c
                                                                configuration
                                                                structures.
                                                              • Initializes QE driver.
                               osInitialize() ->              • osArchDevicesInit
                               osArchDevicesInitialize() -      ialize() calls
                               >                                rionetInitialize
                                                                (); this initializes the
                               rionetInitialize() ->            RIONET driver.
                               bioRegister()                  • In turn,
                                                                bioRegister() is
                                                                called:
                                                               – Takes and registers the
                                                                 driver to the BIO
                                                                 abstraction layer.
                                                               – Returns a pointer to the
                                                                 BIO device handle.
                                                               – Successful registration
                                                                 results in a BIO device
                                                                 handle different than
                                                                 NULL.




SmartDSP OS User Guide                                                                      169
Drivers
RIONET

Table 4.36 Architecture-Independent RIONET API (continued)

             Status         Name                        Description

             Application    osBioDeviceOpen() ->             • Must be first function
             Bring-up       rionetOpen()                       called at this stage.
                                                             • Returns a BIO device
                                                               handle; handle is a
                                                               parameter for calling
                                                               other functions.
                                                             • Calls rionetOpen()
                                                               to open a mailbox.
                            osBioChannelOpen() ->            • Opens a pre-
                            rionetChannelOpen()                allocated BIO device
                                                               channel.
                                                             • Initializes channel
                                                               structure as per
                                                               configuration
                                                               parameters.
                                                             • Calls
                                                               rionetChannelOpe
                                                               n() to open the
                                                               RIONET channel.




170                                                           SmartDSP OS User Guide
Drivers
                                                                                             RIONET

Table 4.36 Architecture-Independent RIONET API (continued)

             Status             Name                               Description

             Application        osBioChannelTx() ->                   • Via a BIO channel,
             Runtime            rionetChannelTx()                       osBioChannelTx()
                                                                        transmits a frame
                                                                        previously opened for
                                                                        transmission.
                                                                      • Calls
                                                                        rionetChannelTx(
                                                                        ) to send a message
                                                                        to the BIO layer.
                                osBioDeviceCtrl() ->                  • osBioDeviceCtrl()
                                rionetCtrl()                             performs control
                                                                        commands on a
                                                                        device.
                                                                      • Calls rionetCtrl()
                                                                        to perform a device-
                                                                        level control function.
                                osBioChannelCtrl() ->                 • osBioChannelCtrl(
                                rionetChannelCtrl()                     ) performs control
                                                                        commands on a
                                                                        channel.
                                                                      • Calls
                                                                        rionetChannelCtr
                                                                        l() to perform a
                                                                        channel-level control
                                                                        function.
                                rionetTxIsr()                         • Calls an interrupt
                                                                        service routine after a
                                                                        packet has been sent.
                                                                      • Packet configured to
                                                                        issue an interrupt.
                                rionetRxIsr()                         • Calls an interrupt
                                                                        service routine after a
                                                                        packet has been
                                                                        received.
                                                                      • Packet configured to
                                                                        issue an interrupt.



           Functionality
           This section details RIONET initialization, runtime, and network stack interactions.

           Initialization
           Follow these steps to initialize RIONET.



SmartDSP OS User Guide                                                                            171
Drivers
RIONET

          1. RIONET initialization header file:
             initialization/arch/msc81xx/include/msc81xx_rionet_init
          2. Enable RIONET mailboxes by defining the following in os_config.h:
             #define MSC81XX_RIONET0 ON
             #define MSC81XX_RIONET1 ON
          3. Enable SRIO by defining the following in os_config.h:
             #define MSC815X_SRIO ON

          NOTE        See “SmartDSP OS API Reference Manual” for a complete description of
                      srio_init_params_t and rionet_init_params_t.

          4. In “mcs81xx_config.c” file, set “srio_init_params_t srio_init_params” for SRIO ports
             initialization. For example,
          srio_init_params_t srio_init_params =
          {
               2,
               {
                 {
                      SRIO_PORT0,
                      SRIO_CONNECTIVITY_MODE,
                      TRUE,
                      NULL,
                      NULL
                 },
                 {
                      SRIO_PORT1,
                      SRIO_CONNECTIVITY_MODE,
                      TRUE,
                      NULL,
                      NULL
                 },
               }
          };




172                                                                    SmartDSP OS User Guide
Drivers
                                                                                            RIONET

           5. In file “mcs81xx_config.c”, set “rionet_init_params_t rionet_init_params_(0/1)” for
              RIONET initialization.

                Set rionet_init_params_t.rionet_flags as follows:
               • Set RIONET_FIXED_SIZE_AND_QUEUE to use a fixed packet size—as used in
                 rionet_init_params_t.frame_size and fixed queue (queue 0) for all incoming traffic.

           NOTE        Use RIONET_FIXED_SIZE_AND_QUEUE mode only with drivers
                       recompiled with CUSTOMER_SPECIFIC_RIONET definition.

               • Set RIONET_DONT_DROP_PACKETS to prohibit RIONET from dropping
                 packets if the RIONET queue is full.
           For example,
           rionet_init_params_t rionet_init_params_0 =
           {
                0,
                INBOUND_FRAME_SIZE_256,
                INBOUND_QUEUE_SIZE_2,
                (OS_NUM_OF_CORES * TEST_NUM_OF_CHANNELS),
                TEST_NUM_OF_TX_FRAMES,
                OUTBOUND_QUEUE_SIZE_0002,
                OUTBOUND_SERVICE_CONTROL_FIX,
                (int8_t)0xFF,
                2 *TEST_NUM_OF_TX_FRAMES,
                2 * TEST_NUM_OF_TX_FRAMES,
                OS_HWI_PRIORITY1,
                OS_HWI_PRIORITY1,
                Rionet0Buffer_b,
                Rionet0Buffer_b + RIONET_BUFFER_SIZE,
                APP_LLD_HEAP,
                0
           };

           NOTE        For correct driver functionality, take note of the following restrictions:
                       — Set tx_queue_size (Tx frame queue size) to comply with BIO restrictions.



SmartDSP OS User Guide                                                                           173
Drivers
RIONET

                      — BIO Tx confirmation queue must be the same size (or larger) than the LLD
                      Tx BD ring (tx_q_sz). Users must ensure (as per the traffic profile) that this
                      restriction is always maintained.

                      — In RIONET the Tx BD ring is shared; therefore, the LLD cannot assert on a
                      misconfiguration.

           6. Rx μ code is loaded during osInitialize(). As described above, the user needs to
              initialize the rionet_init_params_t. The μ code header also contains a HW-defined
              packet size and RIONET version.
           7. Open a RIONET (0/1) device using osBioDeviceOpen().
           8. Create a frame pool using osFramePoolCreate().
           9. Create a buffer pool for the Rx channels.
           10. Open Rx and/or Tx channels—for an open RIONET device—using
               osBioChannelOpen().
           11. Use osBioDeviceCtrl(RIONET_CMD_ENABLE)for the following:
                – To check that all channels/devices are open.
                – To enable QE and SRIO for mailboxes.

           Runtime
           Follow these steps during RIONET application runtime:
           1. Use osFrameGet() for new frame allocations and osFrameBufferNew() for
              new data buffer allocations.
           2. Initialize data buffer and frame information using osFrameAAAA()manipulation
              functions.
           3. Provide packet information for routing in the RIONET application (or LLD) headers.
           4. Use macros to set the correct RIONET application (or LLD) header field; see Table
              4.37. Eight-byte RIONET header structures are shown in Figure 4.5.


Table 4.37 RIONET Header Fields

             RIONET Header Field                   Description
             #define                                 • Sets destination sRIO device ID.
             RIONET_SET_DST_ID(PACKET,
             DATA)

             #define                                 • Sets a destination sRIO mailbox for a
             RIONET_SET_DST_MB(PACKET,                 packet.
             DATA)



174                                                                    SmartDSP OS User Guide
Drivers
                                                                                           RIONET

Table 4.37 RIONET Header Fields

             RIONET Header Field                 Description
             #define                                • Sets a destination RIONET BIO
             RIONET_SET_DST_CH(PACKET,                channel for a packet.
             DATA)
                                                    • QE responsible for moving the
                                                      received packet.
             #define                                • Sets the sRIO port that will transmit a
             RIONET_SET_PHY_PORT(PACKET,              specified message.
             DATA)
                                                    • Only applicable for MSC815x.



Figure 4.5 RIONET Header Structure




           5. Use osBioChannelTx() for frame transmission.
           6. In a non-interrupt mode, use the following to poll an Rx channel,
              osBioChannelCtrl(RIONET_CMD_CHANNEL_RX_POLL).

           RIONET and Network Stack
           The RIONET driver and network stack can work together.

           Rx:

SmartDSP OS User Guide                                                                          175
Drivers
RIONET

               • BIO Rx channel callback function is set to the network stack input point,
                 etherInput().
               • RIONET driver plugs into the network stack when calling etherInput().

             Tx:
               • Transmissions are sent using net stack transmit functions; e.g., udpSend() and
                 tcpSend().


             Precautions
             1. During initialization, users can choose if QE will drop packets on underrun or continue
                with them. Use RIONET_DONT_DROP_PACKETS in the rionet_flags
                field of the rionet_init_params_t structure.

             NOTE       QE continuing with packets is default RIONET μ code behavior that can
                        potentially cause sRIO retry errors. Overriding the default can, however, lead
                        to sRIO controller congestion and retry errors.

             2. When interfacing the network stack, the application must populate the ARP table
                ahead of time as RIONET receive functions cannot deal with ARP discovery packets.

             NOTE       ARP is not supported in RIONET.



             Source Code
             RIONET driver header files and additional libraries:
Table 4.38

              Source                  Type                          Detail

              Library                 Driver                        “SmartDSPlibmsc81xx*_drive
                                                                    rs.elb”

                                      Kernel                        “SmartDSPlibmsc81xx*.elb”

                                      Board Support Package         "SmartDSPdemosstarcorems
                                                                    c81xxads_supportads_project
                                                                    bsp_msc81xxads.elb"




176                                                                      SmartDSP OS User Guide
Drivers
                                                                Time Division Multiplexing (TDM)

Table 4.38

              Source                Type                          Detail

              Files                 Driver Initialization         “SmartDSPinitializationarchm
                                                                  sc815xincludemsc815x_rionet
                                                                  _init.h”

                                    Driver Runtime                "SmartDSPincludearchstarcor
                                                                  emsc815xmsc815x_rionet.h"



             Resource Management
             Note the following Tx and Rx resource management issues:
               • Manage the Tx queue by spinlock.
               • Manage a Tx completion indication using a pre-allocated array (size of Tx queue) on
                 heap; this is indicated in the initialization structure rionet_init_params_t.
               • Each Tx channel requires one each of the following: frame queue and frame pool. No
                 buffer queues or pools are required. For more information see the BIO chapter.
               • Each Rx channel requires one each of the following: frame queue, frame pool, buffer
                 queue, and buffer pool. Channel buffer pools and queues can be the same as those in
                 the BIO device. For more information see the BIO chapter.


             Demo Use Cases
             RIONET driver demos:
               • “SmartDSPdemosstarcoremsc814xrionet”
               • “SmartDSPdemosstarcoremsc814xamc_ecli”
               • “SmartDSPdemosstarcoremsc815xrionet”


Time Division Multiplexing (TDM)
             The SmartDSP TDM driver functions as an SIO device; it belongs to the SIO LLD layer
             (under the SIO layer) that manages data serialization and device registration.


             Features
             TDM is characterized as follows:
               • Implements transfer protocol and data management.



SmartDSP OS User Guide                                                                          177
Drivers
Time Division Multiplexing (TDM)

               • Interface enables communication—among many devices—over a single bus.
               • Interface is composed of four identical but independent TDM modules.
               • Each module supports 256 channels; the channels run at a maximum of 50 Mbps and
                 have a word size of 2, 4, 8, and 16-bits.
               • Manages traffic by allowing only one device to drive the bus for each channel.
               • When a channel is active, each device drives its active transmit channels and samples
                 its active receive channels.
               • System designer must guarantee that there are no conflicts in transmit channel
                 allocation.
               • Used with both linear and nonlinear encoding.
             Operates without any data copying to provide efficient Tx/Rx flow from user application
             to driver; this reduces the application’s required memory space.


             Relevant SoC

             Architecture
             TDM driver only supports a double-buffer paradigm; thus Tx and Rx buffers are divided
             into two parts. The first part is processed by the user application, the second part is
             transmitted or received. TDM implementation follows these steps:
             1. TDM Initialization
             2. Tx/Rx Process
             3. Control Operation


             Data Flow
             TDM Tx/Rx Process
             All sent/received buffers are passed to the user application via the data callback. The data
             callback, a user application function, is supplied to the driver when a channel opens.
             An open channel can be connected as a data callback parameter even if working with the
             same callback for different channels.

             NOTE       Users allocate the handle for the SIO channel and, when opening the channel,
                        can specify it as a parameter.

               • User application, with a channel handle, can call osSioBufferGet() to get a
                 new buffer.

178                                                                        SmartDSP OS User Guide
Drivers
                                          Universal Asynchronous Receiver/Transmitter (UART)

             • User application, before a driver demand, must release the “new buffer” by calling
               osSioBufferPut(). If not, the application error callback function may be called.


           Programming Model
           TDM Initialization
           SmartDSP OS calls tdmInitialize() to initialize the TDM driver. The user
           application should not call this function directly. The TDM driver is initialized if the
           configuration file MSC81xx_TDM0 flag is set to ON.
           Function tdmInitialize() characteristics include the following:
             • Takes the TDM module index (0, 1, or 2) as a parameter.
             • Configures TDM registers according to configuration parameters of the initialization
               structure.
             • Sets application-specific routines for the TDM interrupt handlers.
             • Registers the TDM driver to the SIO layer; consequently, user application can use
               the TDM device via the SIO API.
           Use osSioDeviceOpen()to open the TDM device during the user
           application initialization phase. During Tx and Rx operations, the
           user application opens/closes needed Tx/Rx channels using osSioChannelOpen()/
           osSioChannelClose().


           TDM Control Operation
           SIO API supplies both device and channel control functions to handle all common SIO
           commands; e.g., tdmCtrl() and tdmChannelCtrl().


           Demo Use Cases

Universal Asynchronous Receiver/
Transmitter (UART)
           Introduction
           A universal asynchronous receiver/transmitter, abbreviated UART , is a type of
           "asynchronous receiver/transmitter", a piece of computer hardware that translates data
           between parallel and serial forms. The universal designation indicates that the data format



SmartDSP OS User Guide                                                                                179
Drivers
Universal Asynchronous Receiver/Transmitter (UART)

            and transmission speeds are configurable and that the actual electric signaling levels and
            methods (such as differential signaling etc) typically are handled by a special driver circuit
            external to the UART.


            Features
            SmartDSP OS UART driver provides a full-duplex port for serial communication with
            other devices.
            UART, or SCI, features the following:
              • Implemented as a CIO driver that provides channelized abstraction with other
                peripherals.
              • Uses two dedicated signals to transmit (UTXD) and receive (URXD) data.
              • [Optional] Generates, during reception, an interrupt request when a new character is
                available to the UART data register (SCIDR). The core then reads the character from
                the data register.
            [Optional] Generates, during transmission, an interrupt request when its data register can
            be written with new characters. The core then writes the character to the data register.


            Architecture

            UART Implementation
            UART implementation includes the following steps:
            1. UART Initialization
            2. Transmit Process
            3. Receive Process
            Control Operation


            Data Flow
            Transmit/Dispatch Flow
            The UART Tx process follows these steps:
            1. User application starts the transmit process by calling osCioChannelTx().
            2. CIO driver calls uartChannelTx()with the data pointer and size.
            3. UART driver enables the device for transmission and stores the data pointer and size.
               The driver does not yet copy any characters to the data register.


180                                                                        SmartDSP OS User Guide
Drivers
                                         Universal Asynchronous Receiver/Transmitter (UART)

           4. UART generates a TDRE every time a new character is available in the data register.
           5. uartGeneralIsr(), which handles the interrupt, calls
              uartTransmitIsr() to handle the TDRE event.
           6. The driver, during uartTransmitIsr(), performs the following:
              • writes a single character to the data register; and,
              • notifies CIO that a character was transmitted.
           Driver disables TDRE (until uartChannelTx() is called again) if no characters
           remain for transmission.


           Receive/Consume Flow
           The UART Rx process follows these steps:
           1. User application starts the receive process by calling osCioDeviceCtrl()
           2. UART driver enables the device for reception by creating and enabling a channel
              osCioChannelCtrl()
           3. UART generates an RDRF every time a new character is available in the data register.
           4. uartGeneralIsr(), which handles the interrupt, calls
              uartReceiveIsr() to handle the RDRF event.
           5. The driver, during uartReceiveIsr(), performs the following:
              • requests a free buffer from CIO;
              • reads the character from the data register into the free buffer; and,
              • notifies CIO that a character was received.
           6. If address wakeup mode was configured at initialization, uartReceiveIsr()
              checks a received character before passing it to CIO—to verify that it is an address
              character.

           NOTE       Address characters are not passed to CIO.



           Programming Model
           UART Initialization
           SmartDSP OS calls uartInitialize()to initialize and configure UART registers
           according to configuration parameters in the initialization structure.
             • UART driver is initialized if the configuration file (os_config.h) flag
               MSC81xx_UART_ON flag is set to ON.


SmartDSP OS User Guide                                                                           181
Drivers
Universal Asynchronous Receiver/Transmitter (UART)

              • UART driver initialization header file (msc81xx_uart_init.h) contains the
                UART driver initialization structure definition.
              • User application can create a structure instance, set desired values, and pass them to
                the uartInitialize() function.
              • User application can pass NULL to uartInitialize()and use the default
                UART parameters shown in Listing 4.5.
              • User application can override this configuration by setting desired values in the
                initialization structure.
              • uartInitialize()also registers the UART driver in the CIO layer:
                – Allows user application to use the UART device via the CIO API.
                – Enables UART device for Tx and Rx operations.

Listing 4.5 Default UART Parameters

typedef struct
{
    uint8 wiring_mode = UART_MODE_NORMAL;
     uint32 baud_rate = 57600;
     uint8 parity = UART_PARITY_ON;
     uint8 parity_type = UART_PARITY_EVEN;
     uint8 tcie = UART_TCIE_OFF;
     uint8 data_format = UART_DATA_FORMAT_9BITS;
     uint8 wakeup = UART_WAKE_IDLE_LINE;
     uint8 idle_line_type = UART_ILT_AFTER_START_BIT;
     uint8 rx_addr = 0;
} msc81xx_uart_init_params_t;



            UART Control Operation
            uartCtrl() function handles control commands that enable/disable transmission,
            reception, and other UART interrupts.


            Demo Use Cases
            demosstarcoremsc814xuart
            demosstarcoremsc815xuart




182                                                                     SmartDSP OS User Guide
5
Network Stack
           This chapter explains the SmartDSP OS Network (Net) Stack module. The Net Stack
           module can be used by an application to communicate with other applications or devices.
           This chapter consists of the following topics:
             • Net Stack in SmartDSP OS
             • Supported Protocols


Net Stack in SmartDSP OS
           This topic explains the conceptual model, initialization, and compile-time configuration of
           Net Stack module in the SmartDSP OS.
           This topic consists of the following sub-topics:
             • Conceptual Model
             • Initialization
             • Compile-time Configuration


           Conceptual Model
           The Net Stack module is a software stack that supports frame based protocols, see Figure
           5.1. In addition, the module:
             • acts in conjunction with the Buffer I/O module of SmartDSP OS
             • lets you write user-defined callback functions
             • supports MSC814x (MSC814x ADS) and MSC815x (MSC815x ADS) platforms
           The current implementations are:
             • Ethernet
             • RapidIO® (with SmartDSP OS RIONET headers)

Figure 5.1 SmartDSP OS Net Stack Module




SmartDSP OS User Guide                                                                            183
Network Stack
Net Stack in SmartDSP OS




           The IP layer is the primary protocol in the Net Stack module and almost all the modules
           call it internally. Typically, user do not use the IP module directly. Instead, the protocols
           running on top of the IP layer are utilized. However, there are user level API functions that
           user can call in order to work directly with IP stack (inSetIPCallBack() and ipOutput()).
           The Net Stack module supports both single and multi buffered frames. It is up to the user
           to choose the appropriate Net stack library suitable for the application. Single buffered
           frames supporting targets are compiled with FRAME_SINGLE_BUFFER_ONLY flag.
           Figure 5.2 shows the conceptual model of Net Stack module in SmartDSP OS.




184                                                                       SmartDSP OS User Guide
Network Stack
                                                                      Net Stack in SmartDSP OS

Figure 5.2 Conceptual Model of Net Stack in SmartDSP OS

                             Application Program

                                                                              SmartDSP OS
                 Direct Socket API                   Callback Functions


                                                                             TCP/IP Stack

      ICMP Module      TCP Module         UDP Module       DHCP Module SRTP Module


        ICMP Output      TCP Input          UDP Input          DHCP Input     SRTP Input




        IPSec Module            IP Module
                                                        IP Output


                               IP Input



                       Interface Module (Ethernet)
                                                    Ethernet Output
        ARP
                         Ethernet Input




          COP                             BIO Serializer

                                              osBioChannelTx

                              Serializer Callback




                                     BIO Low Level Driver
                                     LLD Function




SmartDSP OS User Guide                                                                      185
Network Stack
Net Stack in SmartDSP OS


           Initialization
           NOTE       User should use lib/net_debug_xxx.lib for single buffered frames
                      debug version and lib/net_lib_xxx.lib for release version. For multi-
                      buffered frames support lib/net_multi_debug_xxx.lib and lib/
                      net_multi_lib_xxx.lib should be used.

           Following functions are called during initialization of net stack in SmartDSP OS:
              • ifCreate() — Called by the OS to open BIO channels, and call the interface
                specific type initialization function.
              • tcpInit() — Called by the OS to initialize IP TCP socket descriptors, TCP
                descriptors table, and mark all sockets as unused.
              • udpInit() — Called by the OS to initialize IP User datagram protocol (UDP)
                socket descriptors.
              • udpSocket() — Called by the user application to retrieve IP UDP socket
                descriptor.
              • inSetAddr() — Called by the user application to set the local address. It sets all
                network parameters according to the address and sends ARP request.
              • inSetDefGateway() — Called by the user application to set default gateway's
                address for interface.
              • dhcpStart() — Called by the user application to start the DHCP client.
           For ifCreate(), create a memory partition, a frame pool, the transmit and receive BIO
           channels, and specify a MAC address and protocol type (IFT_ETHER and
           IFT_ETHER_VLAN is currently supported). Also initialize all the BIO channels.
           The Net Stack module is hardware independent. It uses the memory partition manager and
           frame pool handlers to create frames (primarily the ICMP and DHCP sub-modules) and
           delete frames after a transmit operation completes.
           The Net Stack module supports Virtual LAN (VLAN) 802.1Q. To enable it, you can call
           the ifCreate() function with a parameter, IFT_ETHER_VLAN. The created VLAN
           interface must be attached to the physical interface that was previously created. After
           attaching the interface, the IP network address and VLAN tags should be defined using the
           source code.
           Refer to SmartDSP OS API Reference Manual for more information.
           After initializing the VLAN interface, the network stack multiplexes all frames arriving
           towards the physical interface, using the VLAN tag of the frame.




186                                                                    SmartDSP OS User Guide
Network Stack
                                                                        Net Stack in SmartDSP OS


           Compile-time Configuration
           You can configure the compile options of the Net Stack module using the net_config_.h
           file.
           The description of the compilation flags in the net_config_.h file is as follows:
             • ON indicates that the feature will be included in the code and OFF indicates that the
               feature will not be included in the code.
             • IF options
                – IF_VALIDATE_LENGTH — Length validation at IF level including Maximum
                  Transmission Unit (MTU) verification.
                – IF_STATISTICS — Statistics gathering for interface layer.
                – INET6 — Ipv6 support (currently not implemented).
             • IP options
                – IP_VALIDATE_LENGTH — Packet length (except MTU), header length, and
                  version validation at IP layer.
                – IP_CHECK_ADDRESS_VALIDITY — IP address validation.
                – IPOPTIONS — IP options handling.
                – INET — Ipv4 support (should always be ON).
                – IP_CHECK_CHECKSUM — Checksum validation of incoming packets (should
                  be ON according to RFC1122).
             • UDP options
                – UDPCHECKSUM — Checksum computing and validation for UDP.
                – UDP_ERROR_CHECKING — Validation of parameters.
                – UDP_STATISTICS — Statistics gathering for UDP layer.
             • RTP options
                – RTP_EXTENSION_HEADER_SUPPORT — Support for RTP header extension.
             • DHCP options
                – DHCP_EVENTS_PRINT — Logging or printing of all the DHCP events.
                – DHCP_DOES_ARP_CHECK — Support for checking the validity of IP address.

           NOTE       You must recompile the network stack module after modifying the
                      net_config_.h file.

           Table 5.1 shows the status of compilation flags in the net_debug.lib and net.lib library
           files.




SmartDSP OS User Guide                                                                            187
Network Stack
Supported Protocols


Table 5.1 Compilation Flag Status in net_debug.lib and net.lib Files

              Compilation Flags           net_debug.lib               net.lib

              IF_VALIDATE_LENGTH          ON                          OFF

              IF_STATISTICS               ON                          OFF

              IP_VALIDATE_LENGTH          ON                          OFF

              IP_CHECK_ADDRESS_VA         ON                          OFF
              LIDITY

              INET                        ON                          OFF

              IP_CHECK_CHECKSUM           ON                          ON

              UDP_ERROR_CHECKING          ON                          OFF

              UDP_STATISTICS              ON                          OFF

              DHCP_SUPPORT                ON                          ON

              DHCP_EVENTS_PRINT           OFF                         OFF



Supported Protocols
            Net Stack module supports the following protocols:
               • IPv6 Network
               • Dynamic Host Control Protocol (DHCP)
               • Real-time Transport Protocol (RTP) or Secure Real-time Transport Protocol (SRTP)
               • Real-time Transport Control Protocol (RTCP)
               • Uniform Data Packet (UDP)
               • Transmission Control Protocol (TCP)
               • Internet Control Message Protocol (ICMP)
               • Internet Protocol (IP)
               • IP Security (IPSec)
               • Address Resolution Protocol (ARP)
               • Management Information Base (MIB)




188                                                                  SmartDSP OS User Guide
Network Stack
                                                                                        IPv6 Network


IPv6 Network
           Net stacks enable applications to communicate with both applications and devices. OSI
           model is the basis for SmartDSP OS net stack implementation; it allows the net to be
           divided into five or seven layers. Each layer, which is composed of several protocols, has
           a specific and independent function. The stack implements the second to fourth layers.
           The IP protocol is implemented in the third (Internet) layer. The net stack supports two
           versions of this protocol:
             • IPv4, the first major version and still the most commonly used.
             • IPv6, the newest (next generation) version.
           Each version features a set of protocols that assist functionality; for example, Neighbor
           Discovery (ND) and ICMPv6 protocols assist IPv6.


           Features
           SmartDSP OS net stack features are listed below:
             • Supports UDP protocol over IPv6.
             • Utilizes ND:
                – Performs discovery of other nodes on the link.
                – Determines node Link Layer addresses.
             • Supports a pinging utility over IPv6 using ICMPv6 echo request and reply.
             • IPv6 stack can run a multi-core environment.
           Currently, the net stack module supports only single buffer frames. Users must compile
           targets using the flag, FRAME_SINGLE_BUFFER_ONLY.


           Architecture
           Components
           The IPv4 net stack was the basis for the IPv6 net stack; both stacks share the second (Link)
           layer. The third and fourth layers are duplicated; each stack has its own protocols and
           functions.




SmartDSP OS User Guide                                                                             189
Network Stack
IPv6 Network

               Design Decisions
               Compilation
               IPv6 net stack is an extension of IPv4. Features include the following:
                 • Users can choose both or just one of these protocols.
                 • Protocol selection is taken at compilation time; the linker removes unnecessary code
                   if only a single protocol is used.
                 • A single channel can support both protocols.
                 • The correct interface is chosen based on the protocol of the received packets.

               Initialization
               The common IPv6 and IPv4 interface has pointers to specific protocol interfaces (ifnet4
               and ifnet6). However, differences do exist between IPv6 and IPv4.
                 • IPv6 has a different network interface, ifnet6.
                 • ifnet6 includes fields relevant to both protocols; e.g., bio_chn_rx.
                 • ifnet_general was defined to support both (and future) protocols on the same
                   channel. Further, it maintains backward compatibility.

               Constraint
               IPv6 address constraints exist due to UEC hardware implementation. Users must assign
               IPv6 addresses whose final 24-bits are different for each channel.


               Data Flow
               Transmit Flow
               The transmit flow, which is invisible to the user. begins from the upper layer of the stack.
               The data is encapsulated with protocol headers while going down the stack:
                 • Application sends data to the UDP layer, the IP layer, and finally to the Ethernet
                   layer.
                 • Performs MAC address resolution.
                 • Initiates address resolution (if unregistered in the ND Table).
                 • Sends an ND packet (while the old frame is pending resolution).
                 • Transmits packet after address resolution.




190                                                                          SmartDSP OS User Guide
Network Stack
                                                                                     IPv6 Network

Figure 5.3 Transmit Flow



                              ICMP6 Output                             TCP/UDP Output

                                Send ND




                                                  IP6 Output




                                              Ethernet Output



    Unresolved
                                                                Multicast/Unicast
                                                                 MAC Address
              ND
       Address Resolution          Resolved




            Receive Flow
            According to the OSI model, every packet contains data encapsulated with headers.
              • Performs header parsing process upon packet receipt.
              • Each layer verifies and validates its packet header.
              • Passes valid packets to the next layer.




SmartDSP OS User Guide                                                                          191
Network Stack
IPv6 Network

Figure 5.4 Receive Flow

                                                Ethernet Input




                                                   Ip6 Input




             ND                      ND                   Echo             Echo            TCP/UDP Input
      Received Neighbor       Received Neighbor           Reply           Request
         Solicitation           Advertisement




             ICMP6 Output                                                         ICMP6 Output
                                                    ND Table                     Send Echo Reply
      Send Neighbor Advertisement


                                                               (For packets waiting to be sent.)



                                                TCP/UDP Output




               Programming Model
               General
               During net stack compilation, set the below noted configurations in net_config.h.
               During the initialization stage, call the functions noted in the table.




192                                                                             SmartDSP OS User Guide
Network Stack
                                                                            IPv6 Network



Table 5.2 DMA Components

            Flow Stage                  Function              Description

            Compilation: net_config.h   INET6                  • Set to ON for
                                                                 IPv6
                                                                 enablement.

                                        IP6_VALIDATE_PACKET     • IP layer header
                                                                  validation.

                                        ND_VALIDATE             • ND header
                                                                  validation.

            Initialization              ifGeneralCreate()       • Initializes the
                                                                  general
                                                                  interface.

                                        if4Create()             • Initializes IPv4
                                                                  interface.
                                                                • Binds it with the
                                                                  general
                                                                  interface.

                                        If6Create()             • Initializes IPv6
                                                                  interface.
                                                                • Binds it with the
                                                                  general
                                                                  interface.

                                        In6SetAddr()            • Called by the
                                                                  user application
                                                                  to set the local
                                                                  IPv6 address.
                                                                • Sets all network
                                                                  parameters as
                                                                  per the address.

                                        udp6Init()              • Initializes IPv6
                                                                  UDP socket
                                                                  descriptors.

                                        udp6socket()            • User calls
                                                                  function to get
                                                                  IPv6 UDP
                                                                  socket
                                                                  descriptor




SmartDSP OS User Guide                                                                193
Network Stack
IPv6 Network

               Example Calling Sequence
Figure 5.5 Example Calling Sequence


                             udp6Init()                     ifGeneralCreate()




                           udp6Socket()                           If6Create()




                                                              In6SetAddr()




               Demo Use
               SmartDSP OS provides several demo use cases that demonstrate net stack usage. For
               example, see the net_ip4_ip6_demo—in the msc815x demo directory—for IPv4 and IPv6
               same channel support. The demos are SmartDSP-specific.


               Appendix Reference
                 • SmartDSP OS API Reference Manual




               Dynamic Host Control Protocol (DHCP)
               The Dynamic Host Configuration Protocol (DHCP) is a network application protocol used
               by DHCP clients to obtain configuration information for operation in an Internet Protocol
               network.
               This topic consists of the following sub-topics:
                 • DHCP Implementation
                 • DHCP Initialization




194                                                                             SmartDSP OS User Guide
Network Stack
                                                                                     IPv6 Network

           DHCP Implementation
           The DHCP protocol allows a host to be configured dynamically. The DHCP client
           implementation is based on RFC 2131, but does not directly implement all the features of
           the protocol. Also, the implementation does not handle all DHCP options (RFC 2132).
           The DHCP Client supports the following options:
             • Option 1 – subnet mask
             • Option 3 – router address
             • Option 51 – address lease time
             • Option 53 – DHCP message type
             • Option 58 – address renewal time
             • Option 59 – address rebinding time
           The DHCP Client should be able to boot both from DHCP and BOOTP servers
           (RFC1534). Figure 5.6 shows the operation of DHCP.

Figure 5.6 DHCP Operation




SmartDSP OS User Guide                                                                         195
Network Stack
IPv6 Network

               DHCP Initialization
               To initialize the DHCP client:
               1. Call the dhcpStart() or dhcpInform() function, as shown below:
                      dhcpStart((struct ifnet*)&ifn,
                      DHCP_DEFAULT_COARSE_TIMER_SECS,
                      DHCP_DEFAULT_FINE_TIMER_MSECS);
               2. The dhcpStart() function opens a UDP socket to broadcast a BOOTP/DHCP
                  request.
               3. An application may poll status of the DHCP client using the dhcpGetState()
                  function, as shown below:
                      dhcpStart(ifnet, DHCP_DEFAULT_COARSE_TIMER_SECS,
                      DHCP_DEFAULT_FINE_TIMER_MSECS, FALSE);
                      while( dhcpGetState(ifnet) != DHCP_BOUND) )
                  DHCP_BOUND means that the DHCP client was configured.

               NOTE       The dhcpInform() function informs the DHCP server about pre-configured
                          IP address.

               4. To handle timeouts and lease time renewal, you can call the following functions:
                    – dhcpFineTmr() — handles network timeouts, packet loss, and server delays.
                      This function is called each DHCP_FINE_TIMER_MSECS seconds.
                    – dhcpCoarseTmr() — enables lease renewal and rebind timeouts. This
                      function is called each DHCP_COARSE_TIMER_MSECS seconds. You must call
                      this function to allow DHCP client to perform the renewal or rebind activity.
                  Because the UPD input goes through the inSetUdpCallBack() function (which
                  sets the callback for UDP input packets), you can call the dhcpReceive() function
                  everytime a packet arrives on DHCP_CLIENT_PORT on the ifnet port. This
                  function is used to deliver all the packets to the DHCP client.


               Real-time Transport Protocol (RTP) or
               Secure Real-time Transport Protocol
               (SRTP)
               The RTP provides end-to-end transmission of real-time (audio and visual) data between
               computers. The SRTP provides security-related features, such as encryption,
               authentication, and integrity to the RTP data.
               This topic consists of the following sub-topics:



196                                                                       SmartDSP OS User Guide
Network Stack
                                                                                         IPv6 Network

              • RTP Implementation
              • RTP Initialization


            RTP Implementation
            Compared to the other protocols implemented by the Net Stack module, RTP has a
            different implementation. This difference stems from RTP's different role in the stack.
            RTP is intended to be malleable to provide the information required by a particular
            application and will often be integrated into the application processing rather than being
            implemented as a separate layer.
            The RTP's implementation is a collection of service routines that help the application build
            an RTP header and analyze the received RTP frames. Using these functions cannot impose
            any constraints on the application side because it is the application's responsibility to
            define the proper use of RTP. The RTP implementation does not use SmartDSP OS
            services in any way.


            RTP Initialization
            To initialize RTP:
            1. You can call the rtpCreateContext() function to create a RTP context (that
               handles transmission of all RTP frames) for all outgoing connections, and
               rtpBuildHeader() to build the RTP headers for an RTP context, see Listing 5.1.

Listing 5.1 Creating a RTP context and building a RTP header

/* Create RTP context with          */
/* sequence number      1234        */
/* ssrc                 5678        */
/* initial time stamp 5665          */
/* payload type         RTP_PCMU_PT */
rtpCreateContext(&rtp_context, 1234, 5678, 5665, RTP_PCMU_PT);

/*Build a header for this context. (10 is a number that timestamp will
grow) */
rtpBuildHeader(&rtp_context, 10, buffer);

            2. You can change an RTP context at run-time using one of the rtpContextxxx()
               functions, such as rtpContextExtensionSet() and
               rtpContextSeqNumberSet().
            3. You can change fields in the RTP header using any of the rtpHeaderxxx
               functions, such as rtpHeaderPayloadLengthGet() and
               rtpHeaderPayloadTypeGet().



SmartDSP OS User Guide                                                                              197
Network Stack
IPv6 Network

               4. For received frames, call the rtpPacketValidate() function to get field values.


               Real-time Transport Control Protocol
               (RTCP)
               The RTP is used in conjunction with the RTCP, which handles transmission of control
               information and Quality of Service (QoS) parameters.
               This topic consists of the following sub-topics:
                 • RTCP Implementation
                 • RTCP Initialization


               RTCP Implementation
               Compared to the other protocols implemented by the Net Stack module, RTCP has a
               different implementation. This difference stems from RTCP's different role in the stack.
               RTCP is intended to be malleable to provide the information required by a particular
               application and will often be integrated into the application processing rather than being
               implemented as a separate layer.
               The RTCP's implementation is a collection of service routines that helps the application
               build an RTCP header and analyze the received RTCP frames. Using these functions
               cannot impose any constraints on the application side because it is the application's
               responsibility to define the proper use of RTCP. The RTCP implementation does not use
               SmartDSP OS services in any way.


               RTCP Initialization
               As an application layer protocol, RTCP is wrapped with TCP functions. It is up to the user
               to create RTCP headers and to parse frames with services supported by SmartDSP OS in
               net_rtcp.h.


               Uniform Data Packet (UDP)
               The UDP is a connection-less protocol which does not provide any error detection and
               recovery. Many Voice over Internet Protocol (VoIP) applications use UDP along with
               RTP to deliver voice packets from source to destination. The UDP provides channel
               multiplexing (ports), and checksums the header and payload.
               This topic consists of the following sub-topics:
                 • UDP Implementation
                 • UDP Initialization
                 • UDP Transmit Process


198                                                                          SmartDSP OS User Guide
Network Stack
                                                                                       IPv6 Network

             • UDP Receive Process


           UDP Implementation
           The UDP protocol implementation has a socket-like API that includes initialization and
           run-time functions for sending frames. All received UDP frames (all ports) go through the
           same user-defined function. Consequently, it is users responsibility to multiplex frames
           according to the sockets.
           The alignment requirements for UDP differ depending on the hardware. The Ethernet
           header is not aligned by size. Therefore, when working with FEC (in which 4-byte
           alignment is required), you must transmit frames with data strictly aligned to 2-byte
           boundaries. In other cases, data must be aligned to a minimum of 2 bytes.

           NOTE       The UDP stack implementation does not handle alignment requirements.
                      Therefore, you must create the necessary alignment.

           If you create UDP frames by calling the udpFrameGet() function and supply a buffer pool
           that is aligned on 4-byte boundaries, the addresses will be aligned on 2-byte boundaries,
           and the address that Ethernet driver receives will be aligned to minimum of 4 bytes. This
           is because the udpFrameGet() function uses the udp_offset offset variable to set offset. By
           default, this value is 42 (UDP + IP + ETHERNET).


           UDP Initialization
           During system initialization:
           1. The udpInit() function is called by the operating system to initialize the UDP. The
              udpInit() function takes as parameters the maximum number of sockets that an
              application can open.
           2. Call the inSetUdpCallBack() function to specify a callback function that
              performs multiplexing of the received frames per port.
           3. An UDP socket is created using the udpSocket() function, which returns a socket
              ID in its parameter. This socket ID is used in all subsequent function calls for data
              transmission and connection.
           Refer to SmartDSP OS API Reference Manual for more information on the UDP
           initialization.


           UDP Transmit Process
           To transmit an UDP frame:
           1. Create an UDP frame and do any of the following:
             • Call udpSend()


SmartDSP OS User Guide                                                                             199
Network Stack
IPv6 Network

                 • Call udpSendTo()
                 • Call a function, such as udpBufferSend() or udpBufferSendTo() that
                   takes a pointer to data. These two functions will copy the data so that there are no
                   alignment requirements.

               NOTE       The udpSend() and udpBufferSend() functions can be called only for
                          connected sockets (sockets connected using udpConnect()) while
                          udpSendTo() and udpBufferSendTo() can be called for any socket.

               2. If udpSend() or udpSendTo() functions return OS_SUCCESS, you should not
                  delete or reuse this frame. If OS_SUCCESS is not returned, it becomes necessary to
                  utilize the frame.
               3. Use osFrameBufferSetWithOffset() to connect a buffer to a frame. The
                  offset is used to reserve a space for the stack headers.
               Another way to create a frame suitable for the UDP is to call the inline function,
               udpFrameGet(). This function creates a frame for the UDP and returns the data address.
               To see how to use the udpBufferSend() function to transmit data to a previously connected
               socket, refer to SmartDSP OS API Reference Manual.

               NOTE       To enhance the performance of the UDP transmit process, it is recommended
                          to call the udpConnect() function before consecutive transmit operations
                          on a socket. This causes the entire UDP-IP header to be cached in the UDP
                          layer. Therefore, the UDP frame can be transmitted directly to BIO.

               The UDP transmit process does not require any data copies. Therefore, unless check
               summing is enabled for the UDP layer, core utilization does not depend on the data size. If
               the first transmit operation is initiated to a new IP address and an ARP request is initiated
               to this address, only the last frame is queued. This situation can cause frame loss in some
               cases. Figure 5.7 shows the UDP transmit process.




200                                                                           SmartDSP OS User Guide
Network Stack
                                                                                     IPv6 Network

Figure 5.7 UDP Transmit Process




           UDP Receive Process
           The UDP can receive frames using a callback function shared by all the UDP sockets.
           Therefore, you must multiplex all the frames at the UDP level, and delete or use each
           received frame.
           If an application identifies that a frame does not belong to it (using the
           udpGetDestinationPort() function), the application should not delete the frame and should
           return OS_FAIL from its callback function. The UDP checks the callback function’s
           return value and if it is ICMP_UNREACH_PORT, the UDP generates the ICMP
           ‘Destination unreachable’ message.

           NOTE       The udpGetDestinationPort() function returns the destination port for
                      a received UDP frame.

           If the UDP receive callback function returns OS_SUCCESS for a frame, the application
           should return the frame to the frame pool by calling the osFrameFree() function. This
           implementation enables you to create an efficient multiplexing mechanisms at the
           application level. Also, this implementation uses sockets for transmission and control
           actions. You can define an UDP callback function using the osSetUdpCallBack() function.
           Refer to SmartDSP OS API Reference Manual for details on defining an UDP receive
           callback function. Figure 5.8 shows the UDP receive process.



SmartDSP OS User Guide                                                                             201
Network Stack
IPv6 Network

Figure 5.8 UDP Receive Process




               Transmission Control Protocol (TCP)
               The TCP is a connection-oriented reliable host-to-host protocol designed to transfer a data
               stream between two hosts with an established connection. The TCP assures that all
               transmitted data is received in the correct order.
               This topic consists of the following sub-topics:
                 • TCP Implementation
                 • TCP Initialization
                 • TCP Transmit Process
                 • TCP Receive Process
                 • Closing a TCP Connection


               TCP Implementation
               The TCP implementation has a socket-like API; it includes initialization and run-time
               functions for transmitting packets. All received TCP packets are sent to a user-defined
               callback function. Data transmissions require an established connection in which the
               connection requests are user-driven or initiated by a remote peer.




202                                                                         SmartDSP OS User Guide
Network Stack
                                                                                       IPv6 Network


           The TCP protocol implementation does not handle the frame offset/buffer alignment
           requirements.
           You must create buffers with the required alignment and initiate a frame offset with the
           correct value. The frames created with tcpFrameGet() have a default offset value of 54
           (TCP + IP + ETHERNET). If you supply a buffer pool that is aligned on 4-byte
           boundaries then the addresses (and user data) will be aligned on 2-byte boundaries.


           TCP Initialization
           During system initialization:
           1. The TCP is initialized by the operating system using the tcpInit() function. The
              maximum number of sockets that an application can open are specified in the
              tcpInit() function.
              The tcpInit() function initializes the IP TCP socket descriptors and TCP
              descriptors table, and marks all sockets as unused. Refer to SmartDSP OS API
              Reference Manual for more details.
           2. Call the inSetTcpCallBack() function to enable tcp reception and to specify a
              callback function that performs multiplexing of the received frames per port.
           3. You can create a TCP socket by calling tcpSocket().
              The tcpSocket() function retrieves an IP TCP socket descriptor and returns a
              socket ID within its parameters. This ID is used in all subsequent function calls for
              data transmission and connection.

           TCP Connection Setup
           A TCP connection can be established between two hosts either by:
             • initiating a connection with a remote TCP server — the application functions as a
               TCP client,
                or by,
             • accepting a remote connection request from a remote TCP client — the application
               functions as a TCP server.
           The TCP client:
             • Allocates/creates sockets using tcpSocket().
             • Binds sockets to a local interface using tcpBind().
             • Connects sockets to a remote peer using tcpConnect().
           To see the source code of establishing a TCP connection using a TCP client, refer to
           SmartDSP OS API Reference Manual.
           The TCP server:


SmartDSP OS User Guide                                                                            203
Network Stack
IPv6 Network

                 • Sends an alert using the tcpReceiveCallBack() function, when a remote host
                   requests a TCP connection.
               The tcpReceiveCallBack() function has two arguments: socket ID and frame. If the socket
               ID is NET_TCP_NO_SOCKET, you can call tcpAcceptInfoGet() to check the connection
               ports and IP addresses. You can accept this connection using the tcpAccept() function,
               refer to SmartDSP OS API Reference Manual for details.

               NOTE       Use the tcpAcceptInfoGet() function only on the frames that are
                          received with the NET_TCP_NO_SOCKET socket ID.



               TCP Transmit Process
               The tcpSend() function is used to transmit an IP TCP frame that has a socket with an
               established connection to the remote destination. You can call tcpFrameGet() to create a
               frame for TCP transmission. The tcpFrameGet() function returns the buffer address. When
               tcpSend() returns OS_SUCCESS, the TCP/IP stack owns the frame. After frame
               transmission, the TCP/IP stack deletes the frame.
               To see how to create a new frame and transmit it to a previously connected socket, refer to
               SmartDSP OS API Reference Manual.
               You must ensure that the noted frame is not reused or deleted when it is in the possession
               of the TCP/IP stack. When tcpSend() does not return OS_SUCCESS, the frame is not
               accepted for transmission by the TCP/IP stack. You can resend or delete the frame
               immediately.
               You can also use the tcpBufferSend() function to send the IP TCP frame to the remote
               destination. You should bind and connect the socket before calling this function. This
               function copies a buffer into a frame structure and is slower than tcpSend().
               To see a sample source code of how to use the tcpBufferSend() function to transmit data to
               a previously connected socket, refer to SmartDSP OS API Reference Manual.


               TCP Receive Process
               You can call the tcpReceiveCallBack() function to receive the incoming TCP frames.
               After calling tcpReceiveCallBack(), activate the TCP using inSetTcpRxCallBack(). A
               return of OS_SUCCESS signals the TCP that a frame was used by the application, and the
               application should release the frame into the pool.
               To see how to use the TCP receive callback function, refer to SmartDSP OS API
               Reference Manual.




204                                                                         SmartDSP OS User Guide
Network Stack
                                                                                        IPv6 Network

           Closing a TCP Connection
           You can close a TCP connection locally or remotely. To close the connection locally, call
           the tcpClose() function. A TCP connection is closed remotely by the remote host, which
           notifies by sending a NULL frame using the receive callback function. After receiving the
           notification, you can call tcpClose() to release the socket to the unused socket pool.


           Internet Control Message Protocol (ICMP)
           Essentially ICMP is a communication protocol between Internet Protocol (IP)
           implementations on two connected systems.
           The ICMP is used by the operating system for sending error messages to the machines on
           network, such as, a requested service is unavailable or a host could not be reached.
           This topic consists of the following sub-topics:
             • ICMP Implementation
             • ICMP Initialization


           ICMP Implementation
           ICMP messages are sent using the basic IP header. The icmpError() function is used to
           transmit an ICMP error message. The following source code shows how to use the
           icmpError() function:
           osFrameHeaderPush(frame, IP_UDP_HEADER_SIZE);
           icmpError((struct ifnet*)&ifn, frame, ICMP_UNREACH,
           ICMP_UNREACH_ADMIN_PROHIBIT, 0);
           You also need to use the inSetICMPCallBack() function to set a callback for the ICMP
           input frames.

           NOTE       The icmpError() function expects an IP frame. Therefore, if you get a
                      frame from the UDP, the offset (IP-UDP) should be removed from this frame
                      before passing it to the icmpError() function.



           ICMP Initialization
           To initialize ICMP, user can define a callback for ICMP input packets with
           inSetICMPCallBack() function.




SmartDSP OS User Guide                                                                          205
Network Stack
IPv6 Network


               Internet Protocol (IP)
               IP is the primary protocol in the Internet Layer of the Internet Protocol Suite and has the
               task of delivering distinguished protocol datagrams (packets) from the source host to the
               destination host solely based on their addresses. For this purpose the IP defines addressing
               methods and structures for datagram encapsulation.
               This topic consists of the following sub-topics:
                  • IP Implementation
                  • IP Initialization
                  • IP Transmit Process
                  • IP Receive Process
                  • IP Reassembly


               IP Implementation
               Smart DSP OS supports IP packets transmission and reception. IP features like
               multicasting, fragmentation, Differentiated Services, and IP-options are not supported.
               IP compilation flags are:
                  • IP_CHECK_ADDRESS_VALIDITY — checks address validity on receiving IP
                    packets.
                  • IP_VALIDATE_LENGTH — checks that the received packets fit to the actual
                    length.
                  • IP_STATISTICS — enable statistics counters for IP.


               IP Initialization
               To initialize IP:
               1. Create a network interface with ifCreate().
               2. Define default gateway address with inSetDefGateway().
               3. Set IP address with inSetAddr().

               NOTE        If support is required for additional transportation layer protocols, call the
                           inSetIPCallBack function.

               The inSetAddr() function assigns the subnet mask of the IP address based on the IP
               address and the class that it belongs to.
               For more information, refer to the Addressing section in RFC791.
               By default, the subnet masks are:


206                                                                            SmartDSP OS User Guide
Network Stack
                                                                                     IPv6 Network

             • Class A: 255.0.0.0
             • Class B: 255.255.0.0
             • Class C: 255.255.255.0
           You can override the default subnet masks by calling the inSetSubNetMask() function to
           provide the interface with a new subnet mask. For example, to set a Class C subnet mask:
           sin.sin_addr.s_addr = 0xFFFFFF00;
           inSetSubNetMask((struct ifnet*)&ifn,(struct sockaddr*)&sin);


           IP Transmit Process
           To transmit IP:
           1. ipOutput() is called from upper layers.
           2. IP addresses are checked and then etherOutput is called.
           3. arpResolve() initiates an ARP request frame.
              If ARP entry is found, frame is sent with the appropriate MAC address. If the IP
              destination address is not found in the ARP table, the IP packet is saved for
              transmission on ARP REPLAY frame reception, see Figure 5.9.




SmartDSP OS User Guide                                                                           207
Network Stack
IPv6 Network

Figure 5.9 IP Transmit Flow




208                           SmartDSP OS User Guide
Network Stack
                                                                                       IPv6 Network

           IP Receive Process
           To receive IP:
           1. Frames received by etherInput are pointed to ipInput() if the ethertype is IP.
           2. ipInput() verifies that the received packets are with local IP address.
           3. Upper layer protocol receive function is called according to the protocol field on the
              received packet.
           4. Unsupported protocols are treated in the user's callback, if any.


           IP Reassembly
           SmartDSP OS supports IP reassembly on layer 3 of the SmartDSP OS network stack.

           NOTE       The reassembly process is wrapped by the osHwiSwiftDisable() and the
                      osHwiSwiftEnable() functions.

           IP reassembly is supported if the packet uses:
             • Ethernet protocol in layer 2, and
             • ICMP, UDP, or TCP in layer 4.
           In addition,:
             • simultaneous arrival of different fragmented packets is supported. For example,
               packet1_fragment1, packet2_fragment1, packet2_fragment2 and
               packet1_fragment1.
             • fragments are reassembled irrespective of the order in which they are received.
             • reassembly requires a software timer for each interface determines the number of
               seconds a packet can live after its first fragment arrives. If the packet is not
               completely reassembled when the timer expires, the packet is discarded, and an
               ICMP message is sent (if the first fragment was received).
             • reassembly offers various error handling mechanisms and software statistics counters
           This topic consists of the following sub-topics:
             • Configuration
             • Basic Flow
             • Error Handling
             • Statistics

           Configuration
           The configuration of IP reassembly generally involves the following procedures:


SmartDSP OS User Guide                                                                            209
Network Stack
IPv6 Network

                 • Enabling Reassembly
                 • Configuring Reassembly
                 • Enabling Error Handling

               Enabling Reassembly
               In SmartDSP OS, IP reassembly works only in Multi-buffer Frame mode. Therefore, to
               have reassembly enabled, make sure that you do not have the following macro defined:
               FRAME_SINGLE_BUFFER_ONLY
               In addition, you should use a multi-buffered frame version of the network stack.

               Configuring Reassembly
               To configure reassembly, use the inReassemblyInit function. Note that this function
               should be called for each specific interface.

               NOTE       The inReassemblyInit function requires a single software timer, which is
                          allocated internally by calling the osTimerFind() function.

               Table 5.3 describes the parameters of the inReassemblyInit function.
Table 5.3 Parameters of the inReassemblyInit Function

                Parameter                          Description

                ifp                                Current interface




210                                                                        SmartDSP OS User Guide
Network Stack
                                                                                    IPv6 Network

Table 5.3 Parameters of the inReassemblyInit Function (continued)

             Parameter                   Description

             ip_reassemble_init          Initialization data structure with following fields:

                                         num_of_frames                 Number of frames that
                                                                       can be reassembled
                                                                       simultaneously

                                         num_of_fragments              Number of fragments
                                                                       that can be
                                                                       reassembled
                                                                       simultaneously for all
                                                                       frames. For example, if
                                                                       you expect to receive up
                                                                       to 5 reassembly frames
                                                                       that can hold up to 10
                                                                       fragments each, you set
                                                                       this value to 50.

                                         heap                          Heap from which to
                                                                       allocate the structures
                                                                       for managing the
                                                                       fragments and the
                                                                       frames

                                         timeout_sec                   Number of seconds a
                                                                       frame is to be kept in
                                                                       the reassembly process
                                                                       after its first fragment
                                                                       arrives. If the frame is
                                                                       not completely
                                                                       reassembled until after
                                                                       the timeout, the frame is
                                                                       released and an
                                                                       ICMP Time Exceeded
                                                                       Reassembly
                                                                       Timeout
                                                                       error message is sent if
                                                                       possible. This is
                                                                       applicable only if the
                                                                       fragment with offset 0
                                                                       has already been
                                                                       received.


            Enabling Error Handling



SmartDSP OS User Guide                                                                           211
Network Stack
IPv6 Network

               To enable error handling, define the IP_REASSEMBLY_CHECK_ERRORS macro in the
               SmartDSPsourcenetincludenet_config_.h file.
               Remember that checking for errors decreases performance and, therefore, is not
               recommended if you do not expect errors.




212                                                                       SmartDSP OS User Guide
Network Stack
                                                                                       IPv6 Network

           Basic Flow
           The following pseudo-algorithm describes the basic flow of the functionality of IP
           reassembly.
           1. User enables reassembly, and configures the number of frames supported, number of
              fragments supported, and the timeout period using the inReassemblyInit
              function.
           2. If a fragment arrives in the ipInput function, follow steps 3 to12.
              A fragment is identified if IP.offset or IP.MF (More Fragments flag) is not equal
              to zero.
           3. Look for a free fragment in the pool of fragments.
              a. If there are none, discard the packet.
                  Once a timeout occurs for a frame that is in the reassembly process, its fragments
                  are released back into the fragment pool, thus freeing resources.
           4. Compare the IP.id, IP.source, IP.destination and IP.protocol fields
              to determine if the frame that this fragment belongs to is being reassembled already.
              a. If the reassembled frame that this fragment belongs to has been found, continue
                 working with that reassembled frame.
              b. Else, look for a free frame in the pool of frames.
                – If one is found, create a new reassembled frame, initialize all the values and start
                  a timer for this frame.
                – If there are none, discard the packet.
                Once a timeout occurs for a frame that is in the reassembly process, its reassembly-
                frames are released back into the frame pool, thus freeing resources.
           5. Add the data length of this fragment to the overall assembled data length of this
              reassembled frame.
           6. If IP.offset equals to zero, it indicates the first fragment.
              Add the header length of this fragment to the overall assembled data length of the
              reassembled frame, since the header of the first fragment in the reassembled frame is
              kept and all other headers are removed.
           7. If IP.MF equals to zero, it indicates the last fragment.
              Set the expected reassembly length to IP.offset + IP.header_length.
           8. Add this fragment to a sorted list of all fragments that belong to the reassembled
              frame.
           9. Check for errors, such as:
             • overlapping fragments
             • a fragment appears after the fragment defined as last


SmartDSP OS User Guide                                                                             213
Network Stack
IPv6 Network

                 • assembled length is larger than maximum IP length.
                  For more information on these errors and their possible resolutions, see Error
                  Handling.
               10. If the expected reassembly length equals the overall assembled data length, create the
                   reassembled frame.
                  Add the data from all fragments to the first fragment and remove the Layer II+III
                  headers in all fragments besides the first fragment.
               11. Set the IP.length value in the reassembled frame to the overall assembled data
                   length, and set the IP.offset in the reassembled frame to zero.
               12. Send the reassembled frame to the next stage according to the IP.protocol value
                   in the ipInput function.

               Error Handling
               Error handling is supported when the IP_REASSEMBLY_CHECK_ERRORS macro is
               defined as ON.
               Note that timeout errors related to reassembly are not included in this section since such
               errors are always enabled as they play an integral part in the reassembly process.
               When you enable error handling using the IP_REASSEMBLY_CHECK_ERRORS
               macro, the following three errors may be detected:
                 • Overlapping Fragments
                 • Fragment Appears After Fragment That is Defined as Last
                 • Assembled Length is Larger Than Maximum IP Length

               Overlapping Fragments
               If sum of the data length and the IP.offset of a fragment is larger than the IP.offset of the
               next fragment, then the respective fragments are considered as overlapping, and the entire
               frame is released with all the fragments. Note that the data length is defined as:
               IP.len–IP.header_length.

               Fragment Appears After Fragment That is Defined as Last
               The fragment with the IP.MF flag set as zero is supposed to be the last fragment in the
               reassembled frame. If a fragment arrives with a higher offset than the fragment defined as
               last, an error is detected and the frame is released with all the fragments.

               Assembled Length is Larger Than Maximum IP Length
               If the assembled length of the reassembled frame is larger than the maximum allowed IP
               length, that is 65535, an error is detected and the frame is released with all the fragments.




214                                                                           SmartDSP OS User Guide
Network Stack
                                                                                          IPv6 Network

            Statistics
            Table 5.4 lists the software statistics counters that IP reassembly in SmartDSP OS
            supports.
Table 5.4 Software Statistics Counters

             Counter Name                            Description

             ips_fragments                           Total number of fragments received

             ips_fragdropped                         Number of fragments discarded or released.
                                                     This includes fragments discarded because of
                                                     any error besides a timeout. If an entire frame is
                                                     discarded, for example due to fragments
                                                     overlapping, each fragment in the frame
                                                     increments the counter.

             ips_fragtimeout                         Number of fragments released because of a
                                                     timeout. Each fragment in the released frame
                                                     increments the counter.

             ips_reassembled                         Total number of reassembled packets



            IP Security (IPSec)
            Internet Protocol Security (IPsec) is a protocol suite for securing Internet Protocol (IP)
            communications by authenticating and encrypting each IP packet of a data stream. IPsec
            also includes protocols for establishing mutual authentication between agents at the
            beginning of the session and negotiation of cryptographic keys to be used during the
            session.
            IPsec is a dual mode, end-to-end, security scheme operating at the Internet Layer of the
            Internet Protocol Suite or OSI model Layer 3. IPsec can be used for protecting any
            application traffic across the internet. Applications need not be specifically designed to
            use IPsec.
            This topic consists of the following sub-topics:
              • IPSec Implementation
              • IPSec Initialization
              • IPSec Transmit Process
              • IPSec Receive Process




SmartDSP OS User Guide                                                                                215
Network Stack
IPv6 Network

               IPSec Implementation
               Net Stack module has targets dedicated for IPSec Support. In Net Stack moduleNet Stack
               module library supporting IPSec all TCP/UDP output streams are encrypted. Encryption is
               done with SmartDSP OS SEC driver. It is the user's responsibility to initialize SEC and
               COP in the application.
               The support for IPSec goes over the Net Stack module. IP, UDP, and TCP call for IPSec
               functions and vice versa.


               IPSec Initialization
               To initialize IPSec:
               1. Initialize SEC.
               2. Call to inConfigIPsec().
               3. Setup for specific security parameters is defined with inConfigIPsecSa() (for in
                  and out security configuration it should be called twice).


               IPSec Transmit Process
                    On output, IPSec is placed between TCP/UDP and IP. Application calls to
                    udpSend()/tcpSend() and the TCP/UDP layer calls for COP abstraction layer
                    with encryption job. After encryption has been finished COP layer calls to
                    espOutputCryptoCb(). The encryption callback calls to ipOutput and frame is
                    sent as an IP packet.
                    Net Stack module does not wait for SEC to finish encryption. The Net Stackstack
                    returns success for transmission request after data has been sent to encryption. Frame
                    transmission over the stack continues once end-of-encryption indication arrives, see
                    Figure 5.10.




216                                                                         SmartDSP OS User Guide
Network Stack
                                                                                    IPv6 Network

Figure 5.10 IPSec Transmit Flow

                                                   Application

                                                                                SmartDSP OS

                                                                               Net Module
                                                             UDP

                                                     udp Send



                                                                                   IP Sec
                                           esp Output          espOutputCryptoCb




                                                                              IP

                                                                   ipOutput




                                                      COP



                                                   SEC LLD




            IPSec Receive Process
                On reception, ipInput calls to espInput. Data is sent for decryption with COP
                abstraction layer. Net Stack module does not wait for SEC to finish decryption. The
                frame processing will be continued once encryption callback is executed by COP.
                The udpInput() is called from espInputCryptoCallback, see Figure 5.11.




SmartDSP OS User Guide                                                                         217
Network Stack
IPv6 Network

Figure 5.11 IP Sec Receive Flow

                                        Application
                                        udp Callback

                                                             SmartDSP OS

                                                             Net Module
                                                         UDP
                                   udpInput




                                        IP Sec                      IP
                                  espInput
                                                       ipInput

                    CryptoCb



                                                       etherInput




                             COP                          BIO



                           SEC LLD                       UEC LLD




                                                       Ethernet HW




218                                                              SmartDSP OS User Guide
Network Stack
                                                                                    IPv6 Network


           Address Resolution Protocol (ARP)
           The Address Resolution Protocol (ARP) is responsible for mapping IP addresses to the
           Media Access Control (MAC) addresses.
           This topic consists of the following sub-topics:
             • ARP Implementation
             • ARP Initialization


           ARP Implementation
           The ARP implementation uses an ARP table of a predefined size
           (MAX_ARP_ENTRIES), which stores the IP and MAC addresses of the machines on
           network.
           The API functions that deal with ARP are:
             • arpInvalidateEntry() — Invalidates ARP entry according to the IP address.
               The following sample source code shows how to use the
               arpInvalidateEntry() function:
              arpInvalidateEntry(ifp, dest.sin_addr.s_addr);

           NOTE       The arpInvalidateEntry() function does not invalidate the TCP/UDP
                      cache for all TCP/UDP sockets.

             • arpResolve() — Resolves IP address according to hw_addr, which is a pointer
               to the MAC address. The arpResolve() function returns a MAC address if one
               exists in the ARP table. Otherwise, the function sends an ARP request to the network
               stack and returns OS_FAIL. The following sample source code shows how to use
               the arpResolve() function:
              uint8_t hw_addr[6];
              status = arpResolve(ifp, NULL, 0xDF1F5FA3, hw_addr);
             • arpAdd() — Adds a new address to the ARP table. To see how to use the
               arpAdd() function, refer to SmartDSP OS API Reference Manual.
             • arpProxyAdd() — Adds a new address to the proxy ARP table.
             • arpAddStatic() - Adds a static entry to ARP table.


           ARP Initialization
           To initialize ARP:
           1. Create an Ethernet interface with ifCreate().
           2. Call inSetAddr().


SmartDSP OS User Guide                                                                         219
Network Stack
IPv6 Network


               NOTE       arpProxyAdd() should be called for each IP address supported by the
                          application.



               Management Information Base (MIB)
               MIB is a type of database used to manage the devices in a communications network.
               This topic consists of the following sub-topics:
                 • MIB Implementation


               MIB Implementation
               Net Stack module partially implements MIB. The implementation is based on RFC2011,
               RFC2013 and RFC2863.
               The netMibGet() function should be used to collect the information for a specific group of
               MIB.




220                                                                        SmartDSP OS User Guide
6
Enabling Software
           An application running on the SmartDSP OS generates many asynchronous and pre-
           emptable events such as interrupts, tasks, and spinlocks. The number of events, which may
           reach thousands per second per core, depends on the application.


Kernel Awareness
           Applications using the SmartDSP kernel awareness (KA) tool can log events with only
           minimal system overhead. KA is a SmartDSP OS component; its graphical interface
           provides log, interrupt, timer, and queue data event views. KA also helps decode complex
           memory dumps if an application crashes.
           The chapter sections explain how to use the KA tool and view related logs: Using
           SmartDSP OS Kernel Awareness Tool and Viewing KA Logs.
           Use the SmartDSP OS KA tool for the following:
             • Directly view the kernel state within the CW IDE.
             • Precisely view and measure the duration of events.
             • View tasks usage and bus utilization.
             • View the order and preemption of events.
             • View core loads.
             • Quickly generate configuration files using the configuration tool.
             • Get event timings in core clock resolution.
             • View buffer pool and queue usage statistics.




SmartDSP OS User Guide                                                                          221
Enabling Software
Kernel Awareness


           Using SmartDSP OS Kernel Awareness
           Tool
           It is necessary to run the CommExpert utility in order to use the SmartDSP OS KA tool.
           The utility allows KA activation and, thereafter, views—in a KA window or log
           visualizer—of data collected from the CW Eclipse IDE.
           Follow these steps to run the utility, activate KA, and access views:
           1. Run the CommExpert utility.
              a. Navigate to the directory <CodeWarrior SC 10.0 Installation
                 directory>SCStarCore_SupportSmartDSPtoolsCommExper
                 t.
              b. Double click CommExpert.exe to open the CommExpert window (see Figure 6.1).

Figure 6.1 CommExpert Window




           2. Activate KA (via the CommExpert window).
              a. In the header menu, select Runtime.
              b. Choose Kernel Awareness –> Listen to KA plug-ins.
              c. START dialogue box, complete with the default Server port number (40000), will
                 appear; see Figure 6.2. The CommExpert server listens on this port to get data from
                 CW Eclipse.
              d. Click Start to initiate the connection with the CommExpert server.



222                                                                     SmartDSP OS User Guide
Enabling Software
                                                                                  Kernel Awareness

Figure 6.2 Server Port Number




               3. Launch the CW IDE.
               4. Open a project in CW. Drag and drop a .project file in the CW IDE.
               5. Build and debug a project.
                  a. In the launch file, under Debugger Options, select the OS Awareness tab; see
                     Figure 6.3.
                  b. Select SmartDSP OS from the Target OS pull-down list.
                  c. Under Log, make the following settings:
                     • Mark Log Display.
                     • Under CommExpert Address, enter the IP address1 in the IP Address text box
                       and 40000 in the Port Number text box.
                     • Mark Log Tasks, Log Software Interrupts, Log Hardware Interrupts, Log Spin
                       Locks, and Log Performance.
                  d. Click Apply (located at the bottom of the screen view).
                  e. Click Debug (located at the bottom of the screen view).
                  f. Program downloads to the simulator.
                  g. Debug view appears; see Figure 6.4.
                  h. Execution halts at the first statement of main().

1.IP   address of the machine upon which the CommExpert server is running.


SmartDSP OS User Guide                                                                              223
Enabling Software
Kernel Awareness


              i. Click on the thread shown in the Debug view. The program counter icon
                   located on the marker bar indicates the next statement for execution.

Figure 6.3 OS Awareness Tab




Figure 6.4 Debug View




224                                                                     SmartDSP OS User Guide
Enabling Software
                                                                             Kernel Awareness




          Marker Bar

           6. View logs.

              a. Click Resume        . The icon is found in the Debug view under the Debug tab.
              b. Debugger executes all program statements.
              c. Debugger completes execution.
              d. CommExpert window displays incoming connection information, one-by-one, as
                 they are received; see Figure 6.5 for an example of SW Interrupts received.




SmartDSP OS User Guide                                                                       225
Enabling Software
Kernel Awareness

Figure 6.5 Incoming Connection Information




           Viewing KA Logs
           View KA logs in the SmartDSP process window that appears after CommExpert finishes
           displaying incoming connection information.
           The SmartDSP process window displays logs for events received after a project has been
           run. The window (see Figure 6.7) has the following log tabs: event log; system log; tasks;
           sw interrupts; hw timers; queues; shared queues; and memory.




226                                                                     SmartDSP OS User Guide
Enabling Software
                                                                                   Kernel Awareness

            event log Tab
            The event log tab displays the following data; see Figure 6.7.
Table 6.1 event log Tab

             Event Data                    Description

             Event names                   Displays running tasks, SWI and HWI, included in the
                                           project.

             Event statistics              Displays data for each thread (SWI/HWI) in the format:
                                              • Current Window Utilization: % of time an event
                                                is active in the current window.
                                              • Entire Log Utilization: % of time an event is
                                                active in the entire log. Displayed in closed
                                                brackets.
                                              • Current Window Number of Activations:
                                                number of times an event was activated in the
                                                current window.
                                              • Entire Log Number of Activations: number of
                                                times an event was activated in the entire log.
                                                Displayed in closed brackets.
                                           Example: 0.00 (0.05%) 0 (192).

             Event graph                   Graph showing duration, type, and priority of an event.

             Left/Right selectors             • Help measure the time length of events on the
                                                graph.
                                              • A running program begins with a background
                                                task and then moves to HWI and thereafter to
                                                SWI.
                                              • The red selector lines, when dragged to a
                                                chosen position, let the user measure the time
                                                between every flow change.
                                              • Figure 6.6 shows selectors placed to measure
                                                the time taken by HWI at a given point in the
                                                program.

             Duration                         • Displays the time period between program
                                                tasks.
                                              • The units of measurement are configurable.




SmartDSP OS User Guide                                                                               227
Enabling Software
Kernel Awareness

Table 6.1 event log Tab

             Event Data                Description

             Core clock                  • Displays time measurement units.
                                         • Manually increase the numbers by clicking on
                                           available units: μsec, msec, ticks, Hz, KHz,
                                           MHz, and GHz.

             Load (core utilization)   Shows core utilization as follows:
                                         • Left side: a selected/visible portion of the log.
                                         • Right side: a graph of core utilization for the
                                           entire log.


Figure 6.6 Left and Right Selectors




Figure 6.7 event log Tab




228                                                                   SmartDSP OS User Guide
Enabling Software
                           Kernel Awareness




SmartDSP OS User Guide                 229
Enabling Software
Kernel Awareness

            system log Tab
            The system log tab (see Figure 6.8) displays columnar data that the user or OS logged
            using the function osReportEvent(); this function returns event reports and error status.
Table 6.2 system log Tab

              System Data                Description

             Severity                       • Designates event severity.
                                             – Example: warning or error

             Event Type                     • Indicates event type.
                                             – Example: error, information, event, and architecture-
                                               specific

             Module                         • Indicates module within which an event occurred.
                                             – Example: DMA, TASK, NET, etc.

             Event Name                     • Specific word relating to an event name.
                                             – Example: OS_ERR_TSK_BLOCKING

             Event Code                     • Numerical code created by an event.
                                             – Example: 0x000EFFDC for
                                               OS_ERR_TSK_BLOCKING
             File                           • Indicates (as a name) the file within which an
                                              event occurred.

             Line                           • Indicates file line within which an event occurred.

             Context                        • [Not in use.]

             Time                           • Time at which an event was reported.
                                             – Example: 1234 [core cycles]

             Remarks                        • User/OS remarks are added to the event report.



Figure 6.8 system log Tab




230                                                                        SmartDSP OS User Guide
Enabling Software
                                                                                    Kernel Awareness

            tasks Tab
            The tasks tab shows the current state of all tasks in the system; see Figure 6.9.
Table 6.3 tasks Tab

             Tasks Data                Description

             number                      • Identifier
                                          – Example: TASK 0, TASK 1, etc.

             name                        • Name
                                          – Example: background, task0, task1, etc.

             status                      • Usage state
                                          – Example: ready, delayed, ready running, and unused.

             priority                    • Priority—the lower the number, the higher the
                                           priority.
                                          – Example: 31, 11, 12

             current stack               • Current stack pointer location (as an address).
                                          – Example: 0x300065f0

             top of stack                • Top of stack location (as an address).
                                          – Example: 0x30006500

             stack size                  • Noted in bytes

             handler                     • Task function

             expiration time             • If idle, tasks will resume after a given number of
                                           system ticks.


Figure 6.9 tasks Tab




SmartDSP OS User Guide                                                                            231
Enabling Software
Kernel Awareness

            sw interrupts Tab
            The sw interrupts tab displays all SWIs defined in the system. SWIs appearing in this
            window do not require compilation with a log-enabled OS library; see Figure 6.10.
Table 6.4 sw interrupts Tab

             SWI Data                       Description

             name                              • Identifier
                                                – Example: SWI 0, SWI 1, ...

             address                           • Location address of the SWI handler.
                                                – Example: 86004cE0.

             handler                           • SWI function

             count                             • Internal variable associated with the SWI.
                                               • Generally indicates the number of times the
                                                 application should execute the SWI.

             status                            • Usage state
                                                – Example: ready, delayed, ready running, and
                                                  unused.

             priority                          • Priority—the lower the number, the higher the
                                                 priority.
                                                – Example: 31, 11, 12

             UID                               • User ID registerd during osSwiCreate().
                                                – Example: 0000


Figure 6.10 sw interrupts Tab




232                                                                     SmartDSP OS User Guide
Enabling Software
                                                                                Kernel Awareness

            hw timers Tab
            The hw timers tab displays the state of the hardware timers. The only hardware timers
            handled are those used via the SmartDSP OS HW Timers API; see Table 6.11.
Table 6.5 hw timers Tab

             HW Timers Data            Description

             name                        • Identifier
                                          – Example: OS_HW_TIMER_0000,
                                            OS_HW_TIMER_0001...

             status                      • Usage state
                                          – Example: used and unused

             mode                        • Operational mode
                                          – Example: periodic, one shot, and free run

             interval                    • Interval timing
                                          – Example: 0x2710 = number of cycles counted by the
                                            timer

             handler                     • Function called when the timer expires.



Figure 6.11 hw timers Tab




SmartDSP OS User Guide                                                                          233
Enabling Software
Kernel Awareness

            sw timers Tab
            The sw timers tab shown displays the state of the software timers; see Figure 6.12.
Table 6.6 sw timers Tab



             name                            • Identifier
                                              – Example: OS_TIMER_...

             status                          • Usage state
                                              – Example: used and unused

             mode                            • Operational mode
                                              – Example: periodic, one shot, and free run

             interval                        • Interval timing
                                              – Example: 0x0001 indicates the number of system
                                                ticks to reload to the timer after it expires.

             handler                         • Function called when the timer expires.

             value                           • Current value
                                              – Example: 0x00000001 = number of ticks till timer
                                                expiration.


Figure 6.12 sw timers Tab




234                                                                      SmartDSP OS User Guide
Enabling Software
                                                                                Kernel Awareness

           queues Tab
           The queues tab displays information related to system queues; see Figure 6.13.
Table 6.7 queues Tab

            queue Data                  Description

            index                         • Identifier
                                           – Example: 0, 1, 2 ...

            status                        • Usage state
                                           – Example: used, unused, empty, and full

            buffer                        • Buffer address used by the queue.
                                           – Example: 0x300093d8.

            size                          • Maximum number of items allowed in a queue.

            items                         • Number of items currently enqueued



Figure 6.13 queues Tab




SmartDSP OS User Guide                                                                      235
Enabling Software
Kernel Awareness

           shared queues Tab
           The shared queues tab displays queue-related information that is shared by all cores in the
           system; see Figure 6.14.
Table 6.8 shared queues Tab

             shared queues Data             Description

             index                            • Identifier
                                               – Example: 0, 1, 2 ...

             status                           • Usage state
                                               – Example: used, unused, empty, and full

             buffer                           • Buffer address used by the queue.
                                               – Example: 0x300093d8.

             size                             • Maximum number of items allowed in a
                                                queue.

             items                            • Number of items currently enqueued



Figure 6.14 shared queues Tab




236                                                                     SmartDSP OS User Guide
Enabling Software
                                                                                  Kernel Awareness

           memory Tab
           The memory tab displays information related to all the buffer pools in the system; see
           Figure 6.15.
Table 6.9 memory Tab

            memory Data              Description

            index                       • Buffer pool identifier
                                         – Example: 0, 1, 2 ...

            address                     • Given buffer pool address.

            block size                  • Byte size of each block in the buffer pool.

            free blocks                 • Available blocks in the buffer pool.
                                         – Example: number of memory blocks the manager can
                                           allocate without entering an underrun state.


Figure 6.15 memory Tab




SmartDSP OS User Guide                                                                              237
Enabling Software
Enablement Utilities


Enablement Utilities
             SmartDSP Host Exchange over Asynchronous Transfer (HEAT) and Enhanced Command
             Line Interface (eCLI) are SmartDSP OS enablement utilities used during application
             development and runtime.
             In addition, CommExpert has a utility for initially configuring an application. See
             SmartDSPtoolsCommExpertdocUser Guide.pdf.
             This chapter details utilities supported by the SmartDSP OS and how they improve OS
             performance:
                • SmartDSP HEAT Runtime Library
                • eCLI Utility


             SmartDSP HEAT Runtime Library
             The SmartDSP HEAT utility provides file access over Ethernet and is compiled in two
             separate modes:


Table 6.10 SmartDSP HEAT Utility

               Usage Modes                   Description

               Override default stdio        Allows applications to benefit from all utilities provided
               function calls.               by the stdio library.
                                             SmartDSP HEAT utility plugs into the lower layers of the
                                             stdio library:
                                                • Overrides default CodeWarrior interface
                                                  (JTAG, using syscall) by calling back into
                                                  SmartDSP HEAT function calls.
                                                • Method requires the following:
                                                 – User application must link to
                                                   heat_lib_stdio.elb or
                                                   heat_lib_stdio_debug.elb.
                                                 – Further, to use the SmartDSP HEAT stdio
                                                   library, add -allow-multiple-definition to
                                                   linker settings.

               Direct use of SmartDSP           • Directly calls SmartDSP HEAT functions
               HEAT function calls.               without linking in the stdio library.
                                                • Calls require an application to link
                                                  heat_lib.elb or heat_lib_debug.elb.




238                                                                         SmartDSP OS User Guide
Enabling Software
                                                                                Enablement Utilities

Table 6.10 SmartDSP HEAT Utility

             Usage Modes                   Description

             Use stdio and SmartDSP           • Add include/heat/os_heat_stdio.h in the
             HEAT with stdio function           source file.
             calls.                           • Use SmartDSP HEAT functions for stdio
                                                lower layers by setting
                                                SMARTDSP_HEAT_USES_STDIO to 1
                                                during compilation.

             Use SmartDSP HEAT with           • Call the function osHeatInitialize()
             both stdio and SmartDSP            using a pointer to the structure
                                                heat_init_params_t.
             HEAT function calls.
                                              • If heat_init_params_t is NULL, then the
                                                osHeatInitialize() function will use
                                                default parameters.
                                              • If an application needs to write to STDOUT or
                                                STDERR, it must also call
                                                osHeatConsoleInitialize().
                                              • Application must call
                                                osHeatStdioInitialize()to plug into
                                                the stdio library.

             Use HEAT from an                 • Set poll_connection to TRUE.
             interrupt handler (ISR).         • Specify heat_poll_function; it should
                                                call osBioChannelCtrl() to poll—until the
                                                server is ready—for incoming packets.



           SmartDSP HEAT Server
           The SmartDSP HEAT server is characterized as follows:
              • DSP runtime library interfaces with a dedicated server running on a remote PC.
              • Server is delivered as a Windows executable and provides both a makefile and
                sources.
              • Files are assumed to be opened in locations relative to the server location.
              • Server executable is found in SmartDSPtoolsheat_server.
              • Run the executable with the flag --help to display all the flags supported by the
                server.




SmartDSP OS User Guide                                                                           239
Enabling Software
Enablement Utilities



Table 6.11 Server Flags

               Server Flags                  Description

               --help                        Creates a help message.

               --thread-count arg (=6)       [Default =6] Sets maximum number of server threads.

               --bind-ip arg                 [Default: 0.0.0.0] Server IP address.

               --port arg (=1254)            [Default: 1254] Server listens to this port number.

               --timeout arg (=10)           [Default: 10] Sets a time factor—waiting period before an
                                             untouched file can be reopened.
                                             Useful for recovering files—if the client died or didn’t
                                             properly close the file.

               --log arg (=error)            [Default: error] Level of log file details [error, info, debug].

               --log-file arg (=log.txt)     [Default: log.txt] Log file name

               --del arg (=no)               [Default: no] Deletes existing log file [y(es), n(o)].



             Server message format includes the following: date (dd/mm/yyyy), time (hh:mm:ss:mili),
             and index. For example:

25/04/2010 12:17:05:069                [dbg] Open file SmartSDP_HEAT_README.txt for
                                             client succeeded
25/04/2010 12:17:05:100                [ERR] File with hash 3862064 failed to close



             eCLI Utility
             eCLI is used for remote debugging of multicore and/or multi-device boards. When
             combined with standard shell, the result is a powerful remote debug tool that enables users
             to invoke predefined callback functions over a standard telnet console. All callback
             functions take two arguments and look similar to this example,
             int cmd_ecli(int argc, char* argv[]);

             NOTE         Standard shell and eCLI are shipped in a single SmartDSP library.




240                                                                             SmartDSP OS User Guide
Enabling Software
                                                                                Enablement Utilities

           Standard Shell
           The SmartDSP standard shell provides the infrastructure for the following:
             • parsing text commands received over TCP/IP via a telnet console; and,
             • returning the results of the invoked functions back to the console.
           To use this functionality the application must perform the following:
           1. Link one of the binaries in SmartDSPlibshell.
           2. Call osShellInit() to initialize functionality.
           3. Call osShellCommandRegister() to register callback functions that can later be
              invoked by remote users.

           SmartDSP provides users with the following standard-shell default commands:


Table 6.12 SmartDSP Standard-Shell Default Commands

            Function/Command               Description

            int cmd_help(int               Displays shell help or, if invoked with an argument, the
            argc, char*                    help text provided when calling
            argv[]);                       osShellCommandRegister().

            int cmd_md(int                 Shows four bytes of memory at a user-specified
            argc, char*                    address.
            argv[]);
                                           From: Displays four bytes of the memory at the address
                                           specified by the user.

            int cmd_mm(int                 Modifies the four bytes of memory to a user-provided
            argc, char*                    value at the user-specified address.
            argv[]);
                                           From: Modifies 4 bytes of the memory at the address
                                           specified by the user to the value provided by the user.

            int cmd_info(int               Provide textual information that is also obtainable by
            argc, char*                    running KA. Refer to the tab sections under “Viewing KA
            argv[]);                       Logs” on page 226.



           eCLI
           eCLI (extended command line interface) adds two additional commands to those
           described above:




SmartDSP OS User Guide                                                                                241
Enabling Software
Enablement Utilities



Table 6.13 SmartDSP eCLI Commands

               Function/Command                 Description

               int cmd_ecli(int                    • eCLI command is a shell command; it
               argc, char* argv[]);                  retrieves user arguments and calls internal
                                                     sub functions.
                                                   • CLI capabilities/functionality are extended
                                                     once a sub program is opened at a user’s
                                                     CLI.

               int cmd_reroute(int              Sets the device to act as a proxy and reroute eCLI
               argc, char* argv[]);             commands multiple cores and devices.



             eCLI handles internal global and local variables that may be used to invoke existing
             functions in the global system table. Local and global variables include the following:


Table 6.14

               Variables                      Description

               e_exec                         Operates basic commands described in Table 6.12.

               e_set                            • Sets system variables to a new value, passed
                                                  by the user.
                                                • It can be used with one parameter to define a
                                                  value; e.g., e_set $a allocates $a as local
                                                  variable with a 0 value.
                                                • It can be used with two parameters. First
                                                  parameter is the variable, second parameter
                                                  is either the value to set or another variable
                                                  from which to copy the value to set;
                                                  e.g., e_set var0[var1|val]
                                                 – Sets var0 with the value of var1 if var 1 is the
                                                   second parameter.
                                                 – Sets var0 with the value of val if val is the second
                                                   parameter.
                                                 – Value can be specified in the following formats:
                                                                   – 0xNUM — hexadecimal
                                                                   – 0dNUM/NUM — decimal
                                                                   – 0bNUM — binary
               e_get                          Prints the variable value; e.g., e_get var.

               e_free                         Frees a local variable; e.g., e_free var.



242                                                                         SmartDSP OS User Guide
Enabling Software
                                                                                 Enablement Utilities

            Function Calls
               • In eCLI, the function return value is optional.
               • Function parameters can be numeric, local, or global variables.
               • Return value can be a local or global variable. For example:
            e_set $a
            $a = osMalloc(0x20,0xec9c0000)
            e_get $a
            where 0xec9c0000 is the enumeration of OS_MEM_LOCAL.


            Reroute
            reroute command reroutes eCLI traffic to a specific core on a specific device. The core
            and device take a same form “as if” the target had evaluated the functions
            osGetCoreID()and osGetDeviceID().
            For example: reroute 1 0 reroutes an IO towards device 1 core 0.


            eCLI and Reroute Initialization
            During initialization, register eCLI and reroute commands as shell commands. The
            complex reroute command requires registration as well as the following:


Table 6.15 eCLI and Reroute Initialization

              Flow Stage                  Description

              Channel initialization      For server and clients.

              Port handling convention    Distinguishes between server and client.

              Reroute initialization         • Use the reroute_enable API; it utilizes
                                               SmartDSP OS server and client resources.
                                             • In the server:
                                              – <semaphore * number of sessions> that handles an
                                                I/O from machine to clients.
                                              – <multiple queues (of 64 bytes per element in the
                                                queue) in the size of {number of session} *10> as
                                                well as the task that handles the I/O coming from the
                                                clients to a machine.
                                             • In each client:
                                              – <(semaphore + event queue + task) * number of
                                                sessions> that handles the TCP connection and the
                                                CLI task.



SmartDSP OS User Guide                                                                             243
Enabling Software
Enablement Utilities

             Demo of eCLI Utility
             Run the eCLI utility through CodeWarrior by following these steps:
             1. Compile all required libraries with the LLT flag (export_table); use the LLT flag
                found in the eCLI demo project.
             2. Run the eCLI demo project.
             3. Run all project cores.
             4. Open telnet using the IP address, 10.0.0.1.
             5. Run reroute 1 1 at the command prompt.
                • reroute command passes eCLI commands to other device cores that are not
                  directly connected to the telnet.
                • a telnet session opening with core 0 on device 0 will transfer all eCLI
                  commands to core 1 on device 1.
             6. Run ecli at the command prompt.
                • Project functions are ordinarily called with a user’s application code (before
                  compilation).
                • Using telnet, project functions can be called at runtime.
             7. Run the below eCLI commands in the command prompt; see Figure 6.16.
                e_set $a
                e_get ecli_demo_counter
                $a = osTaskActivate(ecli_demo_task_handle)
                e_get $a
                osTaskSuspend(ecli_demo_task_handle)
                e_get ecli_demo_counter




244                                                                       SmartDSP OS User Guide
Enabling Software
                                                                            Enablement Utilities

Figure 6.16 eCLI Command Window




              • osTaskActivate() activates the task found in the project code.
                osTaskActivate()displays the following: device ID, core ID, and the CW I/O
                console counter; see Figure 6.17.
              • Upon suspension of the task, the e_get ecli_demo_counter returns a result
                counter to the command window. The counter is not constant; it varies according to
                the execution time between the osTaskActivate() and osTaskSuspend()
                functions.
           8. Exit eCLI using Ctrl-C + ENTER.
              Exit reroute (and return to the main core) by typing exit.




SmartDSP OS User Guide                                                                        245
Enabling Software
Enablement Utilities

Figure 6.17 CodeWarrior I/O Console Window




246                                          SmartDSP OS User Guide
7
Utilities
           There are two kinds of SmartDSP OS utilities: Enablement and Verification and Stimulus.
           IP UDP generator, libSrtp, and MJPEG player are some of the SmartDSP OS verification
           and stimulus utilities that are used to validate your configurations. These utilities are not
           used during runtime but only while bringing up the user application.
           This chapter explains various utilities that SmartDSP OS supports and how these utilities
           operate to improve the performance of the operating system. The chapter consists of this
           section:
             • Verification and Stimulus Utilities


Verification and Stimulus Utilities
           The SmartDSP OS provides the following verification and stimulus utilities:
             • IP UDP Generator Utility
             • Real-time Transport Protocol (RTP) Player Utility
             • libSRTP Utility
             • MJPEG Player Utility
             • CommExpert Utility


           IP UDP Generator Utility
           The IP UDP generator utility of SmartDSP OS is used to test SmartDSP OS Net Demos.
           To use the IP UDP generator utility:
           1. Connect the board to your machine using an Ethernet cross cable.
           2. Set the IP address of the machine to be on the same network as the board is configured.
              In most Net demos, the board's IP address is hard-coded in the code of the demo
              application.
           3. Run the Net demo.
           4. Run IP_UDP_GEN as:
           IP_UDP_GEN <PC IP Address> <Board IP Address> <Number of
           iterations> <Min Datagram Size> <Max Datagram Size>
           For example,


SmartDSP OS User Guide                                                                              247
Utilities
Verification and Stimulus Utilities

              IP_UDP_GEN            223.31.95.163       223.31.95.200          10     800      900
              10000
              You can now use the IP UDP generator program to send as many IP UDP frames to the
              board. The board echoes the frames back to the machine, and the IP UDP generator
              program compares the received data to the transmitted data, and prints the results.


              Real-time Transport Protocol (RTP) Player
              Utility
              The RTP Player utility of SmartDSP OS provides a graphical user interface for
              transmitting real-time data such as audio, video, and simulation among various
              applications. The GUI of the RTP Player divides into the following five tabs, each with a
              specific functionality:
                 • Connection Tab
                 • Record Tab
                 • Codecs Tab
                 • Effects Tab
                 • Statistics Tab


              Connection Tab
              The Connection tab of the RTP Player utility (see Figure 7.1) is used for connecting to a
              DSP. Use the following procedure to specify the settings in the Connection tab to connect
              to a DSP:
              1. Enter the data port of the DSP, in the Data Port text box. The default port number is
                 2000.
              2. Enter the command port of the DSP, in the Command Port text box. The default port
                 number is 1000. These ports help establishing a communication with DSP
                 applications.
              3. Enter the IP address of the DSP, in the IP Address text box. The default IP address is
                 10.0.0.1.




248                                                                       SmartDSP OS User Guide
Utilities
                                                                Verification and Stimulus Utilities

Figure 7.1 Connection Tab




           4. Click Connect to connect to the DSP and Disconnect to disconnect from DSP.


           Record Tab
           The Record tab of the RTP Player utility allows you to save a recording of the RTP stream
           in the .wav format. Use the following procedure to save a recording:




SmartDSP OS User Guide                                                                          249
Utilities
Verification and Stimulus Utilities

              1. Enter the name of the recorded file in the File name text box, as shown in Figure 7.2

Figure 7.2 Record Tab
.




              2. Click Record to start the recording and Stop to stop it. The counter shows the elapsed
                 recorded time.


              Codecs Tab
              The Codecs tab of the RTP Player utility allows you to select audio codecs to use for
              compressing or decompressing digital audio data according to a specified audio format.
              You can select the required codec type and number of channels from the Codec type and
              Number of channels text boxes respectively (see Figure 7.3).




250                                                                       SmartDSP OS User Guide
Utilities
                                                                 Verification and Stimulus Utilities

Figure 7.3 Codecs Tab




           Effects Tab
           The Effects tab of the RTP Player utility allows you to graphically see the audio on the
           Mono and Stereo channels. Do the following to enter the settings:




SmartDSP OS User Guide                                                                           251
Utilities
Verification and Stimulus Utilities

              1. Select the required effects by marking the corresponding check box (see Figure 7.4).

Figure 7.4 Effects Tab




              2. Scroll the slider to the right to increase the intensity of an effect. The minimum
                 intensity of the effect is 1 and the maximum intensity is 10.


              Statistics Tab
              The Statistics tab of the RTP Player utility displays the information related to
              communication statistics (see Figure 7.5).




252                                                                         SmartDSP OS User Guide
Utilities
                                                                  Verification and Stimulus Utilities

Figure 7.5 Statistics Tab




            Following are the parameters of the Statistics tab:
               • Connection Status — Displays the connected/disconnected to/from DSP status
               • Session Source ID — Displays the RTP Session source ID
               • Total Received RTP Packets — Displays the number of RTP packets that have
                 been received from DSP
               • Lost RTP Packets — Displays the number of RTP packets that have been lost
               • Invalid RTP Packets — Displays the number of RTP packets that were corrupted
               • Avg. RTP Jitter — Displays the average deviation from the proper packet rate. The
                 proper packet rate is 1 packet per 20 msec
               • Codec Bit Rate — Displays the proper bit rate of the chosen codec type and channel,
                 as described below:
                 – PCM - Stereo - 256 kbit/sec
                 – PCM - Mono - 256 kbit/sec
                 – A-law - Stereo - 128 kbit/sec
                 – A-law - Mono - 64 kbit/sec
                 – U-law - Stereo - 128 kbit/sec
                 – U-law - Mono - 64 kbit/sec


SmartDSP OS User Guide                                                                          253
Utilities
Verification and Stimulus Utilities

                 • Sound Device Bit Rate — Displays the real bit rate of the sound device


              libSRTP Utility
              The SmartDSP OS libSRTP utility works as a library of the SmartDSP OS. The libSRTP
              library provides an open-source implementation of the Secure Real-time Transport
              Protocol (SRTP). SRTP adds a security feature to RTP by providing encryption and
              authentication to the data transmitted through the RTP.

              NOTE       Please add a note that the utility is based on the open-source source code
                         available at http://srtp.sourceforge.net/srtp.html.

              The set up and execution of libSRTP needs the net demo configuration. You need to set
              the default gateway IP address and the Base IP address, as follows:
              #define DEFAULT_GATEWAY_IP_ADDRESS                      0x0A00008A          /*
              10.0.0.138 */
              #define BASE_IP_ADDRESS                0x0A000001            /* 10.0.0.1 */

              NOTE       The SmartDSP OS IP/UDP stack assumes the standard subnet mask for IP
                         addresses. Therefore, the default demo settings require the 255.255.255.0
                         subnet mask.

              The subsequent topics below describe a demo of how to set up the libSRTP utility and
              then run it.


              libSRTP Set Up
              Use the following procedure to set up the libSRTP utility:
              1. Configure the board’s dip switches. See the MSC8144ADS Quick Start guide to
                 configure the board.
                 a. On the MSC8144ADS board, make sure that SW 2.1 (HOST) is set to OFF (1).
                 b. On MSC8144ADS rev. PILOT, change SW2.8 to RGMII (ON).

              NOTE       This demo requires the pin MUX6 to work; the board cannot be configured by
                         external dip switches only.

              2. Burn the file eeprom_pin_mux6.img into the EEPROM.
              3. Configure the reset Word source as EEPROM using the dip switches.
              4. Ensure that a GETH network cable is connected to the RJ45 D connector.




254                                                                         SmartDSP OS User Guide
Utilities
                                                                 Verification and Stimulus Utilities

           5. Ensure that the other end of the GETH cable is connected to the GETH card of the
              computer or switch.


           libSRTP Execution
           Use the following steps to execute the libSRTP utility:
           1. Run the project,
              SmartDSPdemosstarcoremsc814xnet_srtpsrtp_projectsrt
              p.mcp. Ensure that a connection is established by using the ping command.
           2. Run the tool, SmartDSPtoolslibSRTPserver.bat. The following lines
              appear on the screen:
           >cipher key (hex): a887efd032b38fc0382d0767e9eada58
           >salt key         (hex): f0d91dd8a14bf79e0aad0038bc93
           >auth key         (hex): a84c7b14c93ef256bac3856badf6a9218fe5a906

           NOTE       The above keys correspond to the keys that are used in the demo. These keys
                      are generated by the libSRTP server tool from the master key in the batch
                      file.The same master key also appears in the libSRTP client batch file. You
                      can change the generated keys by changing the master key in both the client
                      and server files.

           3. Run the tool, SmartDSPtoolslibSRTPclient.bat. The server tool
              receives a ‘Hello world’ message. The client tool takes the message from the
              words.txt file present in the SmartDSP/tools/libSRTP folder. The client
              encrypts and authenticates the message and sends it to the demo. The demo decrypts
              the message and changes the first letter each time it is sent. The demo encrypts and
              authenticates the message and sends it to the server, which decrypts it and prints the
              result.


           MJPEG Player Utility
           The MJPEG Player is used to interact with a DSP and show a stream of motion JPEG. The
           MJPEG Player sends .bmp files to the MSC81xx DSP and displays the MJPEG stream in
           the image part of the GUI. Figure 7.6 shows the MJPEG Player window.




SmartDSP OS User Guide                                                                           255
Utilities
Verification and Stimulus Utilities

Figure 7.6 MJPEG Player Window




              You can select the file to be sent to the MSC81xx DSP and can make the following
              choices:
                 • Use the Core enable area to select the cores to participate in the encoding process
                   using the checkboxes. Core 0 is required; others are optional.
                 • Use the Properties area to change the number of frames per second to encode. This
                   allows you to see how it affects the core load and load balancing.
                 • Use the Core color area to select a color for the macro blocks encoded by each core
                   dynamically to show the dynamic load balancing. But you should be aware that this
                   adds to the execution cycles required for frame encoding.




256                                                                        SmartDSP OS User Guide
Utilities
                                                                 Verification and Stimulus Utilities

           The loads of all the cores are displayed graphically over time on the bottom right of the
           window. The current utilization of each of the core is shown graphically in the Application
           Utilization area of the window. The MJPEG Player also displays the system utilization;
           that is, cycles used for encoding divided by the number of cycles in the DSP. For example,
           4 cores running at 1GHz = 4G cycles.


           CommExpert Utility
           The CommExpert utility of the SmartDSP OS is a dialog-based tool. It is used to configure
           and validate the driver and to generate initialization code for MSC8144 devices. The
           CommExpert utility allows you to configure specific MSC8144 device modules, which
           generate C initialization code that runs on the device. The CommExpert utility also
           provides the correct pin muxing value based on the configured drivers.


           CommExpert Interface Design
           The main window of the CommExpert utility displays two panels:
             • Device view
             • Status view

           Device View
           The Device View panel contains the modules of the device that you select for
           configuration. The modules are displayed as blocks and you can configure these modules
           by clicking on them. The panel displays color codes to give information about the status of
           modules. Figure 7.7 shows the status of the modules displayed in the Device View panel.

Figure 7.7 Device View Panel of CommExpert




           Table 7.1 lists the color codes that the Device View panel displays with the corresponding
           status of the module. A module’s configuration can have one status listed in the table.


SmartDSP OS User Guide                                                                            257
Utilities
Verification and Stimulus Utilities


Table 7.1 Status of Modules in Device View Panel

                Color Code            Status                    Description

                Gray                  Not assigned              The module is not configured;
                                                                therefore, no initialization code will be
                                                                generated for it.

                Blue                  Default                   The module is configured but only
                                                                with the default values that the
                                                                CommExpert utility provides. No
                                                                changes were made to the
                                                                configuration.

                Green                 Configured                The module is configured with at least
                                                                one value different from the default
                                                                values.

                Yellow                Disabled by hardware      The module cannot be configured
                                      constraints               because the hardware resources use
                                                                some pins, which are used by another
                                                                module.

                White                 Not supported             The block is not supported.


              In the Device View panel, the silicon devices are divided into the following three
              categories (Figure 7.8):
                 • Character I/O devices (SPI, UART, I2C)
                 • Buffered I/O devices (UEC 0, UEC 1, SRIO)
                 • Stream I/O devices (TDM)




258                                                                        SmartDSP OS User Guide
Utilities
                                                               Verification and Stimulus Utilities

Figure 7.8 MSC8144 Device Modules Parts




           Status View
           The Status View panel displays a tree structure that contains information about all the
           configurations made in a project. The information is organized module-by-module where
           each module has its own structure. Figure 7.9 shows the Status View panel displaying
           module parameters.




SmartDSP OS User Guide                                                                        259
Utilities
Verification and Stimulus Utilities

Figure 7.9 Status View Panel - Module Parameters




              The module parameter window displays the parameter name and its configured value. The
              parameter values can be displayed as a hexadecimal, decimal, or string value. The first
              icon from the left side in Figure 7.9 indicates the value of the module parameter. A module
              parameter can have one of the following values:


                 • Default


                 • Configured
              The second icon from the left in Figure 7.9 indicates the type of the module parameter. A
              module parameter can have one of the following types:


                 • Protocol


                 • Device


                 • Driver


260                                                                        SmartDSP OS User Guide
Utilities
                                                                  Verification and Stimulus Utilities

           The module parameters are grouped into configuration folders. The Status View tree
           structure is updated when a configuration is modified. You can delete some of the
           configuration folders from the Status View panel. A module parameter can belong to one
           of the following configuration folders:


              • Removable (can be deleted)


              • Permanent (cannot be deleted)
           You can either open a module configuration or delete it by right-clicking on the
           corresponding configuration folder and selecting the appropriate option from the context
           menu (Figure 7.10).

Figure 7.10 Open/Delete Module Configuration




           When you select a configuration folder to delete it, a confirmation dialog box appears and
           if the configuration is removable then it gets deleted. If you try to delete a configuration
           where interdependency exists, that is another configuration is dependant on it, then an
           information message appears.


           Module Design Interface
           The module design interface or the module configuration window of the CommExpert
           utility allows you to configure the modules of the MSC8144 device. The module
           configuration window appears when you right-click on the required module configuration
           folder in the Status View panel and select the Open option. The module configuration
           window includes four tabs (Figure 7.11):
              • Protocol — Include parameters that are specific to that protocol and are independent
                of the device.
              • Device — Includes parameters that are specific to a device with their values present
                in the device registers.
              • Driver — Includes parameters that the driver introduces to provide better interaction
                with the device (mainly callbacks).
              • PinMuxing — Is available only for modules that use pin muxion option 1-8. Some
                modules can work only with certain pin muxing options. PinMuxing logic prevents



SmartDSP OS User Guide                                                                             261
Utilities
Verification and Stimulus Utilities

                   you to choose an incompatible pin muxing option with the correct initialization
                   configuration.

Figure 7.11 Module Configuration Window




              Generally, parameters are logically grouped by their functionality. Figure 7.12 shows an
              example of the reception parameters grouped together for the UEC module.

Figure 7.12 UEC Rx and Tx Parameters Window




              Workflow of CommExpert
              This section describes the working of the CommExpert utility for the SmartDSP OS. the
              basic operations of the CommExpert utility are:
                 • Creating a project
                 • Configuring parameters


262                                                                       SmartDSP OS User Guide
Utilities
                                                                 Verification and Stimulus Utilities

             • Generating code

           Creating a Project
           Use the following procedure to create a project using the CommExpert utility:
           1. Select File > New from the main menu. The New project window appears, as shown
              in Figure 7.13

Figure 7.13 New Project Window




           2. Select the required device family from the Silicon family listbox.
           3. Select the required device type for the selected device family from the Silicon type
              listbox.
           4. Select the board constraints for the selected device family from the Board constraints
              listbox.
           5. Select SmartDSP OS from the Operating system drop-down list.
           6. Specify a name for the project in the Project name text box. This field is optional.
           7. Click OK to display the project in the Device View panel (Figure 7.7).
           By default, some modules of the selected device display as configured because without
           these modules, the device will not work.

           NOTE       It is possible to delete the configured system modules even though the device
                      will not work.




SmartDSP OS User Guide                                                                           263
Utilities
Verification and Stimulus Utilities

              Configuring Parameters
              You can configure the parameters of the module by clicking on the required module. The
              Module Configuration window for the selected module appears (Figure 7.11). The
              CommExpert utility contains some restrictions that are imposed by module
              interdependencies and hardware resource allocation. Before configuring a block, you need
              to go through all the panels and determine what is required.
              The CommExpert utility provides module dependencies that exist between the modules
              while configuring a device. Some modules, such as OS & Cores and UEC, cannot be
              configured unless others are already configured. The network interface objects defined in
              the OS & Cores module need an UEC channel to bind to. Therefore, to have network
              interfaces configured, you must first configure the UEC 0 or UEC 1 channels. All the
              interdependencies are displayed by the CommExpert utility for the SmartDSP in various
              forms, such as:
                 • Warning and error messages
                 • Disabled controls on the interface if they cannot be configured
                 • Not allowing deletion from the Status View if a module is in use by another module
              Figure 7.14 shows an example of driver error message window. The driver errors occur
              when input values (in the Module Configuration window) tested with the driver are not
              validated.




264                                                                       SmartDSP OS User Guide
Utilities
                                                                Verification and Stimulus Utilities

Figure 7.14 Driver Error Message Window




           Generating Code
           After configuring the module, use the following procedure to generate the code for that
           module:




SmartDSP OS User Guide                                                                          265
Utilities
Verification and Stimulus Utilities

              1. Select Tools > Generate Code to display the Save As dialog box (Figure 7.15)

Figure 7.15 Save As Dialog Box




              2. Enter the location where you want to save the code on the host system.
              3. Type the name of the file in the File name text box and click Save.
              The file that will be generated is the main initialization file, which contains all the
              parameters that are configured as structures in the Module Configuration window. The
              data that the main initialization file contains is different form driver data, such as network
              interfaces parameters from the OS & Cores module.
              The other important files that are generated are:
                 • os_config.h — Initializes the SmartDSP OS resources such as stack size,
                   interrupts, and timers
                 • msc814x_config.c — Contains initialization structures used by the driver
              Apart from these files, the following additional files are also generated containing all the
              user callbacks configured in the Module Configuration window:
                 • <filename>_ext.h — Contains the definition of the exported data from
                   <filename>.c file



266                                                                          SmartDSP OS User Guide
Utilities
                                                                   Verification and Stimulus Utilities

             • <filename>_aux.h — Contains definition for user callbacks that are configured
               for the drivers
             • <filename>_aux.c — Contains the implementation of the callbacks defined in
               <filename>_aux.h

           NOTE       <filename> is the name of the file you specify in the File name text box in
                      the Save As dialog box.

           On the Driver tab of the Module Configuration window, many modules have a series of
           user callbacks where you can define your own variables and implementation. These
           callbacks are put in a file with the name suffixed by aux to the main file name. This file is
           generated by an auxiliary C file and also an auxiliary header which contains the prototype
           of the user callbacks.

           NOTE       If the generated auxiliary files already exist on the disk, the user application
                      prompts to make a backup of those files so that you do not lose the existing
                      implementation.

           The generated files can then be included in CodeWarrior projects. The package comes
           with a demo test case which has been tested on the device. In the first instance, you can
           integrate the generated files into this project and then test to see how files run on the
           device. The code may be generated over the files from the use case project by generating
           code over the main files of each project file and implicitly rewriting the additional files of
           this project, which uses the SmartDSP Drivers.
           The CommExpert utility provides a quick way of opening a recently used project by
           selecting File > Recent projects from the main menu.




SmartDSP OS User Guide                                                                               267
Utilities
Verification and Stimulus Utilities




268                                   SmartDSP OS User Guide
A
Using C++ with SmartDSP
OS
            To use C++ in SmartDSP OS, make sure that all the C projects are modified to compile
            and link under C++. When compiled under C++, your application is able to use all
            external header files in C++ without interfering with the SmartDSP OS files.

            NOTE      Use SmartDSP OS linker files to enable C++ support when your application
                      uses SmartDSP OS stationery.

            To modify SmartDSP OS linker files do the following steps:
            1. To define ENABLE_EXCEPTION, add ENABLE_EXCEPTION=0x1 in the LCF file
               or add Xlnk -DENABLE_EXCEPTION=0x1 in the linker command line.
               Enables exception handling to work properly.
            2. To support C++ symbols, add the following lines to local_map_link.l3k:
                   _cpp_staticinit_start= originof(".staticinit");
                   _cpp_staticinit_end= endof(".staticinit");
                   __exception_table_start__ = (ENABLE_EXCEPTION)
                   ?originof(".exception_index"):0;
                   __exception_table_end__ = (ENABLE_EXCEPTION)
                   ?endof(".exception_index"):0;
            3. Add .exception segment to local_map_link.l3k, see Listing A.1.

Listing A.1 Adding Support for Exception Handling

SECTIONS {
descriptor_local_data {
.oskernel_local_data
.data
ramsp_0
.oskernel_rom
.rom
.exception




SmartDSP OS User Guide                                                                        269
Using C++ with SmartDSP OS


.exception_index
…..

            4. Add .unlikely segment to os_msc815x_link.l3k, see Listing A.2.

Listing A.2 Adding .unlikely Segment

descriptor_os_kernel_text {
.osvecb
.oskernel_text_run_time
.oskernel_text_run_time_critical
.oskernel_text_initialization
.unlikely
.text
.private_load_text
.default
.intvec
.......

            5. Enable the compiler rtlib at os_msc815x_link.l3k:
               #define USING_RTLIB 1
            6. To enable exception handling, type –Cpp_exceptions on in the To Shell field,
               see Figure A.1.

Figure A.1 Properties Window—Tool Settings Page




            7. For more information on enabling exception handling, refer to How to Compile C
               Source Files section of the StarCore C-C++ Compiler User Guide.




270                                                                  SmartDSP OS User Guide
Index
A                                         Configuring parameters 264
Activating KA 222                         Creating a project 263
Activating task 38                        Generating code 265
Architecture 10                       CommExpert utility 257
ARP 219                               conditional assembly 222
     Implementation 219               COP 99
     Initialization 219               COP Initialization Workflow 89
Asynchronous intercore messaging 63       System 89
                                          User Application 90
B                                     COP Layers 89
                                      COP LLD 89
Background task 40, 69, 71
                                      COP Runtime Workflow 90
BIO Initialization Workflow 84
                                          Job Dispatch 90
    System 84
                                      COP Serializer 89
    User Application 85
                                      Coprocessor (COP) Module 88
BIO Layers 84
                                      Create a queue 60
BIO LLD 84
                                      Creating a new task 37
BIO Runtime Workflow 87
    Receive 88
    Transmit 87                       D
BIO Serializer 84                     Data ID,DID 33, 34
Buffer Management 47                  Device View panel 257
Buffered I/O Module 83                DHCP
                                          Implementation 195
C                                         Initialization 196
                                      DMA 99, 100
Cache configuration 58
                                      Doorbell 167, 168
Cache sweep commands 57
                                      Doorbell API 139
    Asynchronous 58
                                      Drivers 11
    Synchronous 58
Caches 57
Character I/O (CIO) Module 93         E
CIO 99                                eCLI 241
CIO Initialization Workflow 94        eCLI Utility 240
    System 94                         Enablement Utilities 238
    User Application 95               Event queues 71
CIO Layers 94                         Event Semaphores 69
CIO LLD 94                            Extension Point
CIO Runtime Workflow 95                   Documentation 269
    Receive 96
    Transmit 96                       F
CIO Serializer 94                     Features 9
CommExpert


SmartDSP OS User Guide                                                 271
G
Gigabit Ethernet (GETH) 115

H
Hardware Abstraction Layers (HAL) 81
    Conceptual Model 81
    Conceptual Workflow 83
Hardware interrupts, HWI 27, 40, 68
Hardware timers 78
    Configuration 79
Heap 45
Heap structure 46

I
ICMP 205
      Implementation 205
      Initialization 205
Initialization 159
Initialization and Start Up 14
Intercore message queues 66
      Configuration 66
Intercore Messaging 62
Intercore messaging configuration 63
Intercore Options 67
Interrupt Service Routines,ISR 42
Interrupt Sources 26
Interrupt Types 27
Interrupts 26
Introducing Kernel Awareness 221
IP
      Implementation 206
      Initialization 206
      Reassembly 209
      Receive 209
      Transmit 207
IP UDP Generator Utility 247
IPSec 215
      Implementation 216
      Initialization 216
      Receive 217
      Transmit 216




272                                    SmartDSP OS User Guide
K
Kernel 11
Kernel Components 25
Kernel Introduction 25

L
libSRTP Execution 255
libSRTP Setup 254
libSRTP Utility 254
Linker Command File, LCF 52
Linker Guidelines 16

M
MAPLE 150, 159
MAPLE driver
    Runtime 162
MAPLE-B 150
    Initialization 159
Maskable Interrupt 26
Memory Allocation 45
Memory Management Unit, MMU 50
Memory Manager 43
MIB 220
    Implementation 220
MMU Configuration 55
MMU context 34, 53, 55
    Abstraction 53
    Creation 54
MMU exceptions 56
MMU Features 51
MMU Segment 34
MMU segment 51, 55
    Abstraction 51
    Creation 52
Module Configuration window 261
MSI 141

N
Net Stack 12, 183
     ARP 219
     Compile-time Configuration 187
     Conceptual Model 183
     DHCP 194


SmartDSP OS User Guide                273
ICMP 205
    Initialization 186
    IP 206
    IPSec 215
    MIB 220
    RTCP 198
    RTP 196
    SRTP 196
    Supported Protocols 188
    TCP 202
    UDP 198
Non-Maskable Interrupt 26

O
OCeaN DMA 177, 182

P
PEX 141
Platforms 10
Private queues 60
Program ID,PID 33, 34
Protocols 188

Q
Queues 59

R
Real-time Transport Protocol (RTP) Player Utility 248
Reroute 243
RIONET 164
RIONET transmit 166
RTCP 198
     Implementation 198
     Initialization 198
RTP 196
     Implementation 197
     Initialization 197
RTP player
     Codecs tab 250
     Connection Tab 248
     Effects tab 251
     Record tab 249
     Statistics tab 252


274                                                     SmartDSP OS User Guide
RTP player utility 248

S
Scheduler 32
Scheduler operation 33
Shared queues 60
SIO 99
SIO Initialization Workflow 91
     System 92
     User Application 92
SIO Layers 91
SIO LLD 91
SIO Runtime Workflow 93
SIO Serializer 91
SmartDSP HEAT Utility 238
SmartDSP HEAT utility 238
SmartDSP OS driver 99
SmartDSP OS Utilities
     Verification and stimulus 247
Software interrupts, SWI 40, 68
Software Timers 74
Software timers 73
     Configuration 75
Spinlocks 42
SRTP 196
Status View panel 259
Suspending task 38
Synchronized I/O (SIO) Module 91
Synchronous intercore messaging 62

T
Task States 39
Tasks 33
TCP 202
    Closing Connection 205
    Connection Setup 203
    Implementation 202
    Initialization 203
    Receive 204
    Transmit 204
TDM driver
    Initialization 179
    Transmit/Receive 178
Time Division Multiplexing (TDM) 163, 177

SmartDSP OS User Guide                      275
Types of drivers 99
Types of SmartDSP OS Drivers 99

U
UART 179
UART driver
      Receive 181
UDP 198
      Implementation 199
      Initialization 199
      Receive 201
      Transmit 199
UEC 115
UEC frames
      Multi-buffered 116
      Single-buffered 116
Utilities 13
Utilities of SmartDSP OS 247

V
Verification and stimulus utilities 247
Viewing KA Logs 226
     Event Log Tab 227
     HW Timers Tab 233
     Memory Tab 237
     Queues Tab 235
     Shared Queues Tab 236
     SW Interrupts Tab 232
     System Log tab 230
     Tasks Tab 231




276                                       SmartDSP OS User Guide

More Related Content

PDF
J series-chassis-cluster-setup
PDF
Load runner controller
PDF
Team Omni L2 Requirements Revised
PDF
S6_Guide_80752
PDF
Qtp In Depth
PDF
Laravel 4 Documentation
PDF
Vrs User Guide
PDF
Na vsc install
J series-chassis-cluster-setup
Load runner controller
Team Omni L2 Requirements Revised
S6_Guide_80752
Qtp In Depth
Laravel 4 Documentation
Vrs User Guide
Na vsc install

What's hot (20)

PDF
Qtp user-guide
PDF
Aspire 2930
PDF
CONTINUOUS SYSTEMS, NONSTOP OPERATIONS WITH JUNOS
PDF
ZebraNet Bridge Enterprise - Manual do Software
PDF
Spm6600 Dx6i Manual Lo Res
PDF
Pelco c4654 m a-dx-series-client
PDF
Phasor series operating_manual
PDF
Spartan 3e用户手册
PDF
St3300655 lw
PDF
Aspire one series service guide
PDF
Junipe 1
PDF
Car.8000.ingm
PDF
Manual aspire 1810t 1410
PDF
Air os ug_v80
PDF
Faronics Deep Freeze Enterprise User Guide
PDF
Sg248107 Implementing the IBM Storwize V3700
PDF
Implementing the ibm storwize v3700
PDF
Mod mag m2000 manual badger meter electromagnetic flow meter_m-series
Qtp user-guide
Aspire 2930
CONTINUOUS SYSTEMS, NONSTOP OPERATIONS WITH JUNOS
ZebraNet Bridge Enterprise - Manual do Software
Spm6600 Dx6i Manual Lo Res
Pelco c4654 m a-dx-series-client
Phasor series operating_manual
Spartan 3e用户手册
St3300655 lw
Aspire one series service guide
Junipe 1
Car.8000.ingm
Manual aspire 1810t 1410
Air os ug_v80
Faronics Deep Freeze Enterprise User Guide
Sg248107 Implementing the IBM Storwize V3700
Implementing the ibm storwize v3700
Mod mag m2000 manual badger meter electromagnetic flow meter_m-series
Ad

Similar to Smart dsp os_user_guide (20)

PDF
Guia de usuario arena
PDF
Faronics Power Save Enterprise User Guide
PDF
Managing Data Center Connectivity TechBook
 
PDF
Mitsubishi PLC Q series catalogue
PDF
Creating a VMware Software-Defined Data Center Reference Architecture
 
PDF
Epo 450 product_guide_en-us
PDF
Dns320 manual 100
PDF
8000 guide
PDF
ATV320_Modbus_TCP_EtherNet_IP_Manual_NVE41313_02.pdf
PDF
ScreenOS Idp policy creation en
PDF
Man hinh dieu khien
PDF
Presentation data center deployment guide
PDF
Win plc engine-en
PDF
Essbase database administrator's guide
PDF
Cenet-- capability enabled networking: towards least-privileged networking
PDF
Ws deployment guide
PDF
Windows Internals Covering Windows Server 2008 And Windows Vista 5th Edition ...
PDF
Atv32 programming manual
Guia de usuario arena
Faronics Power Save Enterprise User Guide
Managing Data Center Connectivity TechBook
 
Mitsubishi PLC Q series catalogue
Creating a VMware Software-Defined Data Center Reference Architecture
 
Epo 450 product_guide_en-us
Dns320 manual 100
8000 guide
ATV320_Modbus_TCP_EtherNet_IP_Manual_NVE41313_02.pdf
ScreenOS Idp policy creation en
Man hinh dieu khien
Presentation data center deployment guide
Win plc engine-en
Essbase database administrator's guide
Cenet-- capability enabled networking: towards least-privileged networking
Ws deployment guide
Windows Internals Covering Windows Server 2008 And Windows Vista 5th Edition ...
Atv32 programming manual
Ad

Recently uploaded (20)

PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Institutional Correction lecture only . . .
PDF
RMMM.pdf make it easy to upload and study
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Complications of Minimal Access Surgery at WLH
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Lesson notes of climatology university.
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
Pre independence Education in Inndia.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPH.pptx obstetrics and gynecology in nursing
Institutional Correction lecture only . . .
RMMM.pdf make it easy to upload and study
Microbial diseases, their pathogenesis and prophylaxis
Complications of Minimal Access Surgery at WLH
Microbial disease of the cardiovascular and lymphatic systems
VCE English Exam - Section C Student Revision Booklet
2.FourierTransform-ShortQuestionswithAnswers.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Renaissance Architecture: A Journey from Faith to Humanism
Sports Quiz easy sports quiz sports quiz
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Lesson notes of climatology university.
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Pre independence Education in Inndia.pdf
Supply Chain Operations Speaking Notes -ICLT Program

Smart dsp os_user_guide

  • 1. SmartDSP Operating System User Guide Revised: 14 June 2011
  • 2. Freescale, the Freescale logo, CodeWarrior, PowerQUICC, and StarCore are trademarks of Freescale Semiconductor, Inc., Reg. U.S. Pat. & Tm. Off. Processor Expert, QorIQ, and QUICC Engine are trademarks of Freescale Semiconduc- tor, Inc. All other product or service names are the property of their respective owners. © 2009—2011 Freescale Semiconductor, Inc. All rights reserved. Information in this document is provided solely to enable system and software implementers to use Freescale Semicon- ductor products. There are no express or implied copyright licenses granted hereunder to design or fabricate any inte- grated 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 partic- ular 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 dam- ages. “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 “Typ- icals”, 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 de- signed, 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 Semi- conductor product could create a situation where personal 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. How to Contact Us Corporate Headquarters Freescale Semiconductor, Inc. 6501 William Cannon Drive West Austin, TX 78735 U.S.A. World Wide Web http://www.freescale.com/codewarrior Technical Support http://www.freescale.com/support
  • 3. Table of Contents 1 Introduction 9 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Network Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Directory Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Initialization and Start Up. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 SmartDSP OS Linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Guide to the CodeWarrior Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 More About SmartDSP OS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2 Kernel Components 25 Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Interrupt Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 Interrupt Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Scheduler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Task States. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 Background Task. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 Spinlocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Memory Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Memory Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Buffer Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 Memory Management Unit (MMU) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 MMU Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 MMU Segment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 MMU Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 SmartDSP OS User Guide 3
  • 4. Table of Contents MMU Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55 MMU Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56 Caches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57 Cache Sweep Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57 Configuration of Caches in SmartDSP OS . . . . . . . . . . . . . . . . . . . . . . . . . .58 Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .59 Intercore Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62 Configuration of Intercore Messaging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .63 Intercore Message Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66 Configuration of Intercore Message Queues in SmartDSP OS . . . . . . . . . . .66 Intercore Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67 Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68 Event Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .69 Event Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71 OS Tick Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73 Configuration of OS Tick Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73 Software Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74 Configuration of Software Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .75 Hardware Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .78 Configuration of Hardware Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79 3 Hardware Abstraction Layers (HAL) 81 HAL in SmartDSP OS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81 Conceptual Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81 Conceptual Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .83 Buffered I/O (BIO) Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .83 BIO Layers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .84 BIO Initialization Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .84 BIO Runtime Workflow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .87 Coprocessor (COP) Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .88 COP Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89 COP Initialization Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89 COP Runtime Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90 Synchronized I/O (SIO) Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91 SIO Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91 4 SmartDSP OS User Guide
  • 5. Table of Contents SIO Initialization Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 SIO Runtime Workflow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Character I/O (CIO) Module. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 CIO Layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 CIO Initialization Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 CIO Runtime Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 4 Drivers 99 Direct Memory Access (System DMA) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 Resource Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 OCeaN DMA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 QUICC Engine Unified Ethernet Controller (QE UEC). . . . . . . . . . . . . . . . . . 115 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128 Serial RapidIO (sRIO) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 Resource Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 Doorbell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 SmartDSP OS User Guide 5
  • 6. Table of Contents Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139 Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139 Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141 PCI Express (PCIe) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .142 Data Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .144 Resource Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .149 Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .149 Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) . . . . . . . . . . .150 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .150 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .150 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .151 Data Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .152 Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155 Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .164 RIONET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .164 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .164 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .165 Data Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .166 Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .168 Resource Management. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177 Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177 Time Division Multiplexing (TDM) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .177 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .178 Data Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .178 Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .179 Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .179 Universal Asynchronous Receiver/Transmitter (UART). . . . . . . . . . . . . . . . . .179 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .179 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .180 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .180 6 SmartDSP OS User Guide
  • 7. Table of Contents UART Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181 Demo Use Cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 5 Network Stack 183 Net Stack in SmartDSP OS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 Conceptual Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186 Compile-time Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Supported Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 IPv6 Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 Data Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192 Demo Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 Appendix Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 Dynamic Host Control Protocol (DHCP) . . . . . . . . . . . . . . . . . . . . . . . . . . 194 Real-time Transport Protocol (RTP) or Secure Real-time Transport Protocol (SRTP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 Real-time Transport Control Protocol (RTCP) . . . . . . . . . . . . . . . . . . . . . . 198 Uniform Data Packet (UDP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Transmission Control Protocol (TCP). . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 Internet Control Message Protocol (ICMP) . . . . . . . . . . . . . . . . . . . . . . . . 205 Internet Protocol (IP). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 IP Security (IPSec) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215 Address Resolution Protocol (ARP) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 Management Information Base (MIB) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220 6 Enabling Software 221 Kernel Awareness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 Using SmartDSP OS Kernel Awareness Tool . . . . . . . . . . . . . . . . . . . . . . . 222 Viewing KA Logs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 Enablement Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 SmartDSP OS User Guide 7
  • 8. Table of Contents SmartDSP HEAT Runtime Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .238 SmartDSP HEAT Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .239 eCLI Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .240 7 Utilities 247 Verification and Stimulus Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .247 IP UDP Generator Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .247 Real-time Transport Protocol (RTP) Player Utility . . . . . . . . . . . . . . . . . . .248 libSRTP Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .254 MJPEG Player Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .255 CommExpert Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .257 A Using C++ with SmartDSP OS 269 Index 271 8 SmartDSP OS User Guide
  • 9. 1 Introduction The SmartDSP Operating System (OS) is a Real Time Operating System (RTOS) that, in addition to providing drivers for the MSBA8100 processor, also runs on the following StarCore DSP-based processors: • MSC8101 • MSC812x • MSC814x • MSC815x/MSC825x The StarCore CodeWarrior (CW) Development Studio includes SmartDSP OS royalty- free source code. Further, SmartDSP OS has a high-level Application Programming Interface (API) that lets users develop integrated applications for StarCore processors. This chapter provides information about SmartDSP OS—its features, architecture, startup processes and more. • Features • Architecture • Directory Structure • Initialization and Start Up • SmartDSP OS Linker • Guide to the CodeWarrior Documentation • More About SmartDSP OS Features In SmartDSP OS, most functions are written in ANSI C. However, when needed, Assembly optimizes time-critical functions by maximizing StarCore’s multiple execution units. Other SmartDSP OS features include the following: • small memory footprint ideal for high-speed StarCore processors • priority-based event-driven scheduling (triggered by user applications or HW) • dual-stack pointer for exception and task handling • inter-task communication using queues, semaphores, and events. SmartDSP OS User Guide 9
  • 10. Introduction Architecture Architecture SmartDSP OS design is Cooperative Asymmetric Multi-Processing (CAMP)-based: • cores run their own OS instances; and, • OS manages shared resources and supports inter-core communication. SmartDSP OS also provides an SMP scheduler for MSC814x and MSC815x architectures. The following sections explain different components of SmartDSP OS architecture: • Platforms • Kernel • Drivers • Network Stack • Utilities Platforms Table 1.1 lists SmartDSP OS-supported platforms. Table 1.1 SmartDSP OS-supported Platforms Platform Specific Targets MSC815x/MSC825x • MSC8158/MSC8157 • MSC8156/MSC8154/ MSC8152/MSC8151 • MSC8256/MSC8524/ MSC8252/MSC8251 MSC814x • MSC8144 • MSC8144E • MSC8144EC MSC812x • MSC8122 • MSC8126 • MSC8102 MSC810x • MSC8101 • MSC8103 MSBA8100 Supported via MSC8144 libraries 10 SmartDSP OS User Guide
  • 11. Introduction Architecture Kernel The SmartDSP OS kernel is well-suited for multi-core processors and applications. The kernel has these features: • supports HW and SW interrupts • supports spinlocks to protect critical multicore data • allows user-defined interrupt handlers • Memory Management Unit (MMU) supports HW memory protection SmartDSP OS kernel components: • Caches • Hardware Abstraction Layer (HAL) • Inter-core messaging • Interrupts (HW, SW, and virtual) • MMU • Memory Manager • Message and event queues • Scheduler • Semaphores • Spinlocks • SW and HW timers • Tasks Drivers The SmartDSP OS provides a unified cross-device API for the support of generic HW drivers. Further, it supports drivers providing HW support for relevant Systems-on-a- Chip (SoC): • Direct Memory Access (DMA) • On-chip Network DMA (OCeaN DMA) • Ethernet – TSEC – Quick Engine (UEC) • Serial Rapid Input/Output (sRIO) – RIONET SmartDSP OS User Guide 11
  • 12. Introduction Architecture – Doorbells – eMSG • PCI Express (PEX) • MAPLE • Time Division Multiplexing (TDM) • I2C or Generic I2C • SPI or Generic SPI • Universal Asynchronous Receiver/Transmitter (UART) • Direct Slave Interface (DSI) • CPRI • SEC NOTE An SoC is an integrated circuit (IC) containing a core processor, special function processors, multiple memories and buses, standards-based peripherals, custom logic, and mixed-signal components. Together, these features communicate over a dedicated communication infrastructure. Network Stack The SmartDSP OS has its own network stack that is used by applications to communicate with other applications or devices. The SmartDSP OS network stack supports these protocols: • Address Resolution Protocol (ARP) • Dynamic Host Configuration Protocol (DHCP) • Internet Control Message Protocol (ICMP) • Internet Control Message Protocol (ICMP) IPv6 • Internet Protocol v4 (IPv4) • Internet Protocol v6 (IPv6) • IP Security (IPSec) • Neighbor Discovery • Real-time Transport Protocol (RTP) or Secure RTP (SRTP) • RTP Control Protocol (RTCP) or Secure RTCP (SRTCP) • Transmission Control Protocol (TCP) • Trivial File Transfer Protocol (TFTP) 12 SmartDSP OS User Guide
  • 13. Introduction Directory Structure • User Datagram Protocol (UDP) Utilities The SmartDSP OS provides utilities used to develop applications for StarCore processors: Table 1.2 Utilities Utility Function Configuration tool Configures SmartDSP OS (os_config.h). UDP/IP packet generator Create UDP/IP random packets (with customizable parameters). SRTP client/server MJPEG player Supports motion JPEG modules. RTP player Support RTP modules. SmartDSP Host Exchange over Supports Ethernet remote file access. Asynchronous Transfer (HEAT) server CommExpert Generates initialization code for supported DSPs. Directory Structure The SmartDSP OS is part of the StarCore CodeWarrior Development Studio and is found in the directory, StarCore_SupportSmartDSP. Table 1.3 lists SmartDSP subdirectories. Table 1.3 SmartDSP Subdirectories Subdirectory Content demos Sample projects for supported platforms. drivers C source and header files for compiling a driver library. include C header files used by SmartDSP OS components. SmartDSP OS User Guide 13
  • 14. Introduction Initialization and Start Up Table 1.3 SmartDSP Subdirectories Subdirectory Content initialization C source and header files used for OS initialization. lib Compiled libraries used by SmartDSP OS components. source C source and header files for building compiled libraries. tools Utilities provided by SmartDSP OS, doc OS documentation files and device-specific documentation. Initialization and Start Up The SmartDSP OS uses a specified sequence of function calls during initialization. Table 1.4 Initialization Stage Description Environment Initialization 1. CW startup file begins execution. 2. Calls SmartDSP OS hooks, global variables, and MMU. 3. Jumps to application’s main() function. • Based on the SmartDSP OS option, select from the Build Settings page. • SmartDSP OS linker files are included in a project. See Initialization for more information. SmartDSP OS Initialization Main() function calls osInitialize() function. 14 SmartDSP OS User Guide
  • 15. Introduction Initialization and Start Up Table 1.4 Initialization Stage Description Application Initialization • Main() function initializes user application. • Sample applications, under the demo directory, use appInit(). Application Startup • Main() function starts user application. • Creates background task in osStart() function. • Switches to pending task with the highest priority. SmartDSP OS User Guide 15
  • 16. Introduction SmartDSP OS Linker SmartDSP OS Linker This section details Initialization and Guidelines. Initialization Table 1.5 describes the SmartDSP OS linker files that are included in your project if you select the option to include SmartDSP OS in the new project wizard. Table 1.5 SmartDSP OS Linker Files File Type Linker Files Description Application-dependant memory_map_link.l3k Splits memory into local/ shared regions. local_map_link.l3k Maps local sections to the memory. os_msc815x_link.l3k Primary application- dependent file. SmartDSP OS MSC815x- os_msc815x_link_mmu_def SC3850 MMU specific ines.l3k attribute definitions os_msc815x_link_defines MSC815x .l3k internal memory map os_msc815x_link_app.l3k SmartDSP OS segment attribute definitions os_msc8156_linker_ads_d ADS (DDR) efines.l3k memory map NOTE See the following guides for information on linker error messages and troubleshooting: 16 SmartDSP OS User Guide
  • 17. Introduction SmartDSP OS Linker – StarCore SC3000 Linker User Guide for sc3000-ld linker (.l3k) – StarCore SC100 Linker User Guide for sc100-ld linker (.lcf) Guidelines This section lists guidelines for using StarCore Linker: 1. Consider the following if modifying the physical location of local and shared data. a. Consider performance issues; e.g., local_non_cacheable is currently in M2 memory. b. Check that program sections—used during initialization (before and during MMU programming)—maintain 1x1 virtual-to-physical mapping. c. Ensure that the segments .att_mmu, .oskernel_local_data, and .oskernel_local_data_bss are all local per core and confined by symbols _VirtLocalData_b, _LocalData_size, and _LocalData_b (memory_map_link.l3k). Symbols initialize the MMU and the stack thus enabling C code to run properly. 2. Consider the following if there is insufficient space in a specific memory location. a. Check if all allocated space is truly required. b. Check if there is a memory space or MMU alignment issue. Re-align MMU by modifying the linker command file such that larger sections/ segments link first; this provides better aligned base addresses. c. Check if memory is truly lacking. If so, move non-critical portions to a distant memory. 3. SmartDSP OS uses on-chip memory by default. • DDR is not essential on a board. • If necessary, a portion of the OS can be moved to the DDR. 4. Changes to the linker command file: • If the debugger is still unable to reach the main()function, then there may be an issue of insufficient space at a specific memory location. 5. Memory allocated from a SmartDSP OS-managed heap: • May provide better linking flexibility. 6. Global variables: • If not set in a specific section then they will be placed in .data or .bss. 7. Asymmetric linking (supporting device): • Allows symbols to be linked to sections yet unmapped by all cores. SmartDSP OS User Guide 17
  • 18. Introduction Guide to the CodeWarrior Documentation • Allows cores to link symbols to different physical memories and/or implementations Guide to the CodeWarrior Documentation Following table provides a guide to the documentation included in the CodeWarrior for StarCore DSPs product. The table’s first column identifies a document’s type: Getting Started, User Guide, or Application Note. For late-breaking information about new features, bug fixes, known problems, and incompatibilities, read the release note, which is in this folder: installDirSC NOTE All the information in the PDFs is duplicated in the IDE’s online help. To display online help, start the IDE and select Help > Help Contents. Table 1.6 Guide to the CodeWarrior Documentation Document Document Name Description PDF Name Type PDF Location: installDirSC Getting CodeWarrior for Explains how to install the Quick Start Started StarCore DSPs - CodeWarrior software on a for StarCore DSPs.pdf Windows Edition Windows PC Quick Start Getting Installing Service Explains how to install a service Service Pack Updater Started Pack for pack or an update for your Quick Start.pdf CodeWarrior CodeWarrior software running Tools - Quick on the Windows platform. Start Getting CodeWarrior Explains how to convert a CodeWarrior Started Project Importer classic CodeWarrior project Project Importer Quick Start into an Eclipse IDE project Quick Start.pdf Getting Targeting the Explains how to set up the Quick Start for Started MSC8157ADS MSC8157ADS board, install MSC8157ADS.pdf Board - Quick CodeWarrior Development Start Studio, and use this software to create, build, and debug a simple project that targets this board. 18 SmartDSP OS User Guide
  • 19. Introduction Guide to the CodeWarrior Documentation Table 1.6 Guide to the CodeWarrior Documentation (continued) Document Document Name Description PDF Name Type Getting Targeting the Explains how to install Quick Start for Started MSC8157ISS CodeWarrior Development MSC8157ISS.pdf Simulator - Quick Studio and use this software to Start create, build, and debug a simple project that targets the MSC8157ISS simulator. Getting Targeting the Explains how to install the Quick Start Started MSC8156ADS CodeWarrior software, prepare for MSC8156ADS.pdf Board - the MSC8156ADS board, and Quick Start then create, build, and run a simple MSC8156 project Getting Targeting the Explains how to install the Quick Start Started MSC8156ISS CodeWarrior software and how for MSC8156ISS.pdf Simulator - to use this software to create, Quick Start build, and run a simple MSC8156 project Getting Targeting the Explains how to install the Quick Start Started MSC8154ADS CodeWarrior software, prepare for MSC8154ADS.pdf Board - the MSC8154ADS board, and Quick Start then create, build, and run a simple MSC8154 project Getting Targeting the Explains how to install the Quick Start Started MSC8144ADS CodeWarrior software, prepare for MSC8144ADS.pdf Board - the MSC8144ADS board, and Quick Start then create, build, and run a simple MSC8144 project Getting Targeting the Explains how to set up the Quick Start for P2020- Started P2020-8156 AMC P2020-8156 AMC board, install 8156 AMC.pdf Board - Quick CodeWarrior Development Start Studio, and use this software to create, build, and debug a simple project that targets the MSC8156 side of this board. Getting Multicore Trace Exlpains how to collect trace Quick Start for Started and Profiling of data on multiple cores of a Multicore Tracing.pdf an MSC8156 project after creating, building, Target - Quick and running a project on an Start MSC8156 target. SmartDSP OS User Guide 19
  • 20. Introduction Guide to the CodeWarrior Documentation Table 1.6 Guide to the CodeWarrior Documentation (continued) Document Document Name Description PDF Name Type Getting Using the Explains how to set up the Ethernet TAP Started Ethernet TAP Ethernet TAP probe and create, Quick Start.pdf Probe - build, and debug a simple Quick Start StarCore project that uses this device. Getting CodeWarrior IDE Introduces the interface of the Eclipse Quick Started -Quick Reference Eclipse-based CodeWarrior Reference Card.pdf Card IDE and provides a quick reference to its key bindings PDF Location: installDirSCHelpPDF User CodeWarrior for Provides answers to the most StarCore FAQ Guide.pdf Guide StarCore DSPs - frequently asked questions Frequently Asked about the CodeWarrior IDE and Questions the StarCore build tools. User Freescale Eclipse Documents Freescale’s general Freescale Eclipse Guide Extensions Guide extensions to the Eclipse IDE. Extensions Guide.pdf NOTE: This document may describe features that are not available in the CodeWarrior for StarCore DSPs product; further, the figures show a typical user interface, which may differ slightly from that of the StarCore product. User StarCore DSPs Documents the StarCore- Targeting Guide Targeting Manual specific features of your StarCore DSPs.pdf CodeWarrior product User StarCore Explains how to use runsim and StarCore Simulator Guide Simulator the StarCore simulators to: User Guide.pdf User Guide develop software, profile code, and perform speed and size tradeoff analyses User Profiling and Documents the CodeWarrior Profiling and Analysis Guide Analysis Profiling and Analysis tools, Users Guide.pdf User Guide which provide visibility into an application as it runs on the simulator or hardware 20 SmartDSP OS User Guide
  • 21. Introduction Guide to the CodeWarrior Documentation Table 1.6 Guide to the CodeWarrior Documentation (continued) Document Document Name Description PDF Name Type User StarCore ABI Defines a set of standards for StarCore ABI Guide Reference ensuring interoperability Reference Manual.pdf Manual between conforming CodeWarrior for StarCore software components, such as, compilers, assemblers, linkers, debuggers, and assembly language code User StarCore Documents the StarCore StarCore C-C++ Compiler Guide C/C++ Compiler C/C++ compiler User Guide.pdf User Guide User StarCore Documents the intrinsic StarCore C-C++ Compiler Guide C/C++ Compiler functions the StarCore C/C++ Intrinsics Reference Intrinsics compiler provides. Manual.pdf Reference Manual User EWL C Documents the Embedded EWL C Reference.pdf Guide Reference Warrior C Library, Freescale’s ANSI-compliant implementation of the C standard library User EWL C++ Documents the Embedded EWL C++ Reference.pdf Guide Reference Warrior C++ Library, Freescale’s ANSI-compliant implementation of the C++ standard library User StarCore Documents the StarCore StarCore Assembler Guide Assembler User assembler User Guide.pdf Guide User StarCore Documents the StarCore StarCore SC3000 Linker Guide Linker (SC3000) SC3000 linker, the default User Guide.pdf User Guide linker for MSC8156 device. SC3000 linker command files have the .l3k extension. User StarCore Documents the StarCore StarCore SC100 Linker Guide Linker (SC100) SC100 linker. SC100 linker User Guide.pdf User Guide command files have the .lcf extension. SmartDSP OS User Guide 21
  • 22. Introduction Guide to the CodeWarrior Documentation Table 1.6 Guide to the CodeWarrior Documentation (continued) Document Document Name Description PDF Name Type User SmartDSP OS Explains how to develop SmartDSP OS Concepts Guide User Guide programs for the SmartDSP OS User Guide.pdf User SmartDSP OS Documents the SmartDSP OS SmartDSP OS API Guide API Reference API — the functions, structures, Reference Manual.pdf Manual and classes used in SmartDSP OS programs User Ethernet TAP Explains how to use the Ethernet TAP Guide User Guide Ethernet TAP probe Users Guide.pdf User USB TAP Explains how to use the USB TAP Users Guide.pdf Guide User Guide USB TAP probe Application AN3436 - Explains how to verify boot over AN3436.MSC81xx Ethernet Note MSC81xx Ethernet for the MSC8144 Boot Test.pdf Ethernet Boot Test Application AN3788 - Explains how to use the AN3788.SC.Compiler Note Overlay Support StarCore compiler’s support for Overlay Support.pdf in StarCore overlays and includes some Compiler example tool configurations Application AN3899 - Explains how to use an AN3899.MSC8156 SC3000 Note Using the SC3000 linker control file (LCF) LCF.pdf SC3000 Linker to define the memory layout for Control File for applications that run on the MSC8156 MSC8156 device Applications Application AN4099 - Explains how to use your AN4099.Gearshift Note Setting CodeWarrior tools to set Points.pdf GearShift Points GearShift points Application AN4108 - Explains how to create a AN4108.Config Note Creating a Project CodeWarrior project that treats CodeWarrior IDE for that Treats an an MSC8156ADS board as if it MSC8156 Deriv.pdf MSC8156ADS as contained an MSC8154 or if Populated by an MSC825x variant of the MSC8154 or MSC8156 MSC825x 22 SmartDSP OS User Guide
  • 23. Introduction More About SmartDSP OS Table 1.6 Guide to the CodeWarrior Documentation (continued) Document Document Name Description PDF Name Type Application AN4120 - Explains how to tune existing C AN4120.Tuning C Code for Note Tuning C code for optimal performance SC DSPs.pdf Language Source on Freescale StarCore-based Code for the DSPs and platforms. StarCore DSP More About SmartDSP OS SmartDSP is the chosen OS for Freescale's highly optimized SW libraries—libraries supporting baseband, video, voice and other DSP applications. Freescale and its SW partners—by offering a wide variety of SW libraries optimized on FSL's DSP platforms—enable efficient product development. The SW libraries support both up-to-date and legacy voice and video codecs. Included in the SW libraries are optimized baseband kernel libraries. SmartDSP OS is based on optimized kernels; their unique FSL DSP capabilities enable users to develop highly effective SW applications. All DSP libraries are implemented on SmartDSP OS—to make use of its rich feature set while maintaining expected levels of efficiency and performance. For more information on Freescale DSP SW libraries, visit www.freescale.comdsp. SmartDSP OS User Guide 23
  • 24. Introduction More About SmartDSP OS 24 SmartDSP OS User Guide
  • 25. 2 Kernel Components An OS kernel is an interface between user applications and HW components. The SmartDSP OS kernel has these features: • Predictable and realtime oriented as it is comprised of a preemptive, priority-based, single core with an event-driven scheduler. • Provides interrupt handling, memory management, and task scheduling. • Allows both user and OS code to be executed in HW and SW interrupts, and tasks. • Supports a dual-stack pointer—it uses both exception and normal stack StarCore pointer registers. • Supports multi-core by executing an SDOS instantiation on each core and allowing inter-core communication and synchronization. • Provides an API and functionality for most DSP core and DSP subsystem components. This chapter details the following SmartDSP OS kernel components. • Interrupts • Scheduler • Tasks • Spinlocks • Memory Manager • Memory Management Unit (MMU) • Caches • Queues • Intercore Messaging • Intercore Message Queues • Events • OS Tick Timers • Software Timers • Hardware Timers SmartDSP OS User Guide 25
  • 26. Kernel Components Interrupts Interrupts An interrupt triggers a new event while an interrupt handler executes and services an interrupt request. An SoC can have multiple levels of interrupt concentrators; the kernel program them during application bring-up and runtime. For example, • MSC8101, MSC812x — GIC, LIC, and PIC • MSC814x, MSC815x — GCR and EPIC SmartDSP OS uses the ESP stack pointer for interrupt handling. SC processor interrupts are either MI or NMI: • MI – Application can ignore the interrupt request. – Priorities can vary between interrupt sources. • NMI – Interrupt request is critical. – Interrupt handler must execute. Consider the following SC interrupt characteristics: • StarCore SR calls osStart() from main()to enable interrupts. • User NMI ISR should not call OS functions guarded by disabling and enabling interrupts; e.g., osHwiSwiftDisable() and osHwiSwiftEnable(). – Prevents data or code corruption. – Based on the broken assumption of atomicity in these code portions—a false assumption in NMI. NOTE Ensure that SoC-level NMIs, such as NMI_B and virtual NMIs, are NOT triggered during kernel initialization [prior to calling osStart()]. Interrupt Sources SmartDSP OS interrupts are primarily generated from a single origin. MSC814x interrupt sources include the following: • SC3400 core includes trap-generated interrupts (used for SW interrupts), illegal instructions, and debug exceptions. • DSP subsystem includes MMU, cache, and timer interrupts. • DSP SoC includes peripheral-generated interrupts, VIRQ, and external interrupts lines. 26 SmartDSP OS User Guide
  • 27. Kernel Components Interrupts Interrupt Types SmartDSP OS kernel supports HWI and SWI interrupts. NOTE An application can define stack size in the os_config.h file using definition, #define OS_STACK_SIZE <size>. An interrupt runs on a dedicated stack, StackStart[]. Hardware Interrupts HW devices such as DMA, OCeaN DMA, and Ethernet controllers can generate HW interrupts. In SmartDSP OS kernel, the OS interrupt dispatcher handles HW interrupts in one of these ways: • Calls an OS interrupt handler. • Calls an OS interrupt handler before the interrupt calls a user-defined interrupt handler. • Calls a user-defined interrupt handler. NOTE OCeaN DMA is the on-chip network DMA. See demosstarcoremsc815xuart for more information. HW interrupt characteristics include the following: • Every interrupt handler should return void, and receive a single parameter. • The received parameter is part of the interrupt registration; it is set at registration time. • The parameter can act as a global variable pointer; the variable may change over the course of an application. • Application-provided interrupt handles must be given a HW interrupt function; this is allocated upon registering the HW interrupt handle. • HW interrupt prototype function: typedef void (*os_hwi_function)(os_hwi_arg). • HW interrupts are HW platform-specific thus SmartDSP OS kernel contains header files specific to given HW platforms. For example, – msc814x_hwi.h header file defines HW interrupts for the MSC814x platform. – msc815x_hwi.h header file defines HW interrupts for the MSC815x platform. SmartDSP OS User Guide 27
  • 28. Kernel Components Interrupts SmartDSP OS kernel features include the following: • Supports edge and level HW interrupts. • MMU exception interrupts are hardwired for edge mode. • An application can define edge and level HW interrupts as follows: – #define LEVEL_MODE – #define EDGE_MODE • Enables high priority interrupt handlers to finish before low priority interrupt handlers begin executing. – Respectively, parameters OS_HWI_PRIORITY0 and OS_HWI_LAST_PRIORITY specify the highest and lowest priority for HW interrupts. – Number of priorities depends on PIC or EPIC. • Interrupt controller is located in the DSP subsystem of these processors: – MSC8101, MSC812x — PIC – MSC814x, MSC815x — EPIC • Maximum number of HW interrupt priorities: – SC140-based SoC = 7 – SC3400/SC3850-based SoC = 31 – See SC3850/SC3400 DSP Core Reference Manual. Table 2.1 lists SmartDSP OS HW interrupt module functions. 28 SmartDSP OS User Guide
  • 29. Kernel Components Interrupts Table 2.1 Functions Available for Hardware Interrupts Flow State Name Description Kernel bring up (the user osHwiInitialize() Initializes all interrupt application does not call these handlers to default ones functions specifically. Instead, and enables all NMI in osInitialize() calls these EPIC (where functions based on the supported). parameters from os_config.h and configurations from msc81xx_config.c) Application bring up osHwiCreate() Installs an interrupt handler in the OS dispatcher. It sets the interrupt priority in the interrupt assignment register and enables the interrupt. Application tear down osHwiDelete() Detaches an interrupt handler from the OS dispatcher. Listing 2.1 shows how an application installs a hardware interrupt in the OS dispatcher. 1. Application calls the kernel interrupt handler, osHwiCreate(). 2. Kernel interrupt handler sets interrupt priority in the interrupt assignment register and enables the interrupt. See SmartDSP OS API Reference Manual for more information. Listing 2.1 Installing a HWI in the OS Dispatcher os_status osHwiCreate(os_hwi_handle hwi_num, os_hwi_priority priority, os_hwi_mode mode, os_hwi_function handler, os_hwi_arg argument); SmartDSP OS User Guide 29
  • 30. Kernel Components Interrupts Software Interrupts A SWI is a program-generated interrupt. SmartDSP OS kernel supports nesting SWIs with HWIs and other priority SWIs. Any HWI or high priority SWI preempt a low priority SWI. • Highest priority SWIs are specified by parameter OS_SWI_PRIORITY0. • Lowest priority SWIs are specified by OS_SWI_PRIORITY15. An application, using the definition #define OS_TOTAL_NUM_OF_SWI <num> in the os_config.h file, can specify the number of SWIs per core. The SWI prototype function is typedef void (*os_swi_function)(os_swi_count); NOTE An array of SWI handlers is allocated from the OS_MEM_LOCAL heap. There is a memory penalty if too high a value is set. Table 2.2 lists SmartDSP OS SWI module functions. Table 2.2 Available SWI Functions Flow State Name Description Kernel bring up (the user osSwiInitialize() Initializes the software application does not call these interrupts module. functions specifically. Instead, osInitialize() calls these functions based on the parameters from os_config.h and configurations from msc81xx_config.c) Application bring up osSwiFind() Finds the first available software interrupt number. osSwiCreate() Attaches an interrupt handler to a software interrupt. 30 SmartDSP OS User Guide
  • 31. Kernel Components Interrupts Table 2.2 Available SWI Functions Flow State Name Description Application runtime osSwiActivate() Activates the given software interrupt. osSwiCountSet() Sets the count of the given software interrupt. osSwiCountInc() Increments the count of the given software interrupt and activates it. osSwiCountDec() Decrements the count of the given software interrupt. This function also activates the software interrupt if the count is zero after the operation. Application tear down osSwiDelete() Detaches the given software interrupt from its handler. Listing 2.2 shows how to create a SWI using functions osSwiFind() and osSwiCreate(). • SWI, g_swi_holder1, is generated with the highest priority. • An interrupt handler, foo, services the interrupt request. Refer to SmartDSP OS API Reference Manual for more information. Listing 2.2 Creating a SWI osSwiFind(&g_swi_holder1); status = osSwiCreate(foo, //software interrupt function g_swi_holder1, //software interrupt number OS_SWI_PRIORITY0, //software interrupt priority 50); //user Id if (status != OS_SUCCESS) OS_ASSERT; osSwiCountSet(g_swi_holder1, 100); status = osSwiActivate(g_swi_holder1); OS_ASSERT_COND(status != OS_SUCCESS); void foo(os_swi_count count) SmartDSP OS User Guide 31
  • 32. Kernel Components Scheduler { uint16_t self; if (count != 100) OS_ASSERT; status = osSwiSelf(&self); if (status != OS_SUCCESS) OS_ASSERT; status = osSwiDelete(self); if (status != OS_SUCCESS) OS_ASSERT; } Scheduler A scheduler determines when a specific task or a process must utilize the CPU. In the SmartDSP OS kernel, the scheduler is preemptive and event driven; that is, an event, such as an interrupt, triggers the scheduler to switch to the next higher priority task or process. The SmartDSP OS kernel does not enforce time slots or any other mechanism of load balancing. In SmartDSP OS, each core has its own scheduler. The scheduler handles the events in this priority order: 1. NMI 2. HWI 3. SWI 4. Tasks In other words, the scheduler considers an NMI as the top priority event, and a task as the lowest priority event. Software interrupts can be activated by hardware interrupts, other software interrupts, and by tasks. Software interrupts can be preempted by hardware interrupts or higher-priority software interrupts. Hardware and software interrupts can be nested. The idle or background task has the lowest priority, and it should never end. It can include user code and is preempted by software interrupts as well as hardware interrupts and higher priority tasks. Figure 2.1 shows an example of how the scheduler operates with a single background task in the SmartDSP OS kernel. A higher-priority SWI runs to completion before a lower- priority SWI executes. SWIs are preempted by any HWI or a higher-priority SWI. Hardware interrupts always have priority over software interrupts. Hardware and software interrupts can be nested, and the priorities of each are considered. Figure 2.1 SmartDSP OS Scheduler Operation 32 SmartDSP OS User Guide
  • 33. Kernel Components Tasks In Figure 2.1, the SmartDSP OS Scheduler operates as follows: 1. A HWI with priority 0 (the highest) activates a SWI with priority 8. 2. The SWI with priority 8 waits for HWI with priority 0 to finish. 3. Another HWI with priority 4 is activated as soon as HWI with priority 0 finishes – the HWI with priority 4 is scheduled before the pending SWI with priority 8 (all HWI are scheduled before SWI). 4. The HWI with priority 4 begins executing. 5. The HWI with priority 4 activates another SWI, with priority 6. 6. SWI with priority 6 is scheduled before the pending SWI with priority 8 (SWI with higher priority preempt SWI with lower priority). 7. The SWI with priority 6 begins executing. 8. The SWI with priority 8 begins executing after SWI with priority 6 finishes. Tasks A task represents a specific part of a larger program that is currently loaded in memory. Each task in the SmartDSP OS kernel has its own: • priority. • stack and therefore a set of core registers. • PID and DID (where supported). • name. SmartDSP OS User Guide 33
  • 34. Kernel Components Tasks • private data. A task in the SmartDSP OS kernel is: • different from SWIs and HWIs because a task has its own context and stack. • attached to the core on which it was created. The minimum and default number of tasks in the SmartDSP OS kernel is one. An application can override this setting in the os_config.h file using this definition: #define OS_TOTAL_NUM_OF_TASKS <num> Tasks cannot be shared between cores or stolen. A task can sleep and/or yield the core. An array of task handlers will be allocated off of the OS_MEM_LOCAL heap; therefore you should be aware of the memory penalty of defining too many tasks. The OS_TASK_PRIORITY_HIGHEST and OS_TASK_PRIORITY_LOWEST parameters respectively specify the highest and the lowest priority for tasks. In addition, an application can use the following parameters for specifying a priority other than the highest and the lowest: • OS_TASK_PRIORITY_01, • OS_TASK_PRIORITY_02, • … • OS_TASK_PRIORITY_30 The maximum number of priorities for tasks is 32. An application can create multiple tasks with the same priority that will be scheduled in round-robin. The SmartDSP OS kernel implements cooperative and priority-based scheduling among tasks. The priority of a task can be changed during run time by calling the osTaskPrioritySet() function. This function can be called from any context, HWI, SWI, or by another task. An application can prohibit the scheduler from switching to a higher priority task by locking it. Locking will prevail even if the dispatcher is invoked due to some other event such as a HWI. Use these functions to lock and unlock the scheduler, respectively: • osTaskSchedulerLock() • osTaskSchedulerUnlock() The SmartDSP OS kernel assigns each task with a unique program ID (PID) or data ID (DID) wherever supported in MMU. However, tasks can share a PID and/or a DID if an application specifically adds them to a SmartDSP OS MMU context using these functions: • osTaskMmuDataContextSet() • osTaskMmuProgContextSet() An MMU context defines a PID or DID (depending on the type of context) as well as the set of enabled MMU segments. By default, all tasks have the set of segments enabled in the system context. A task is not required to belong to the same program and data contexts. 34 SmartDSP OS User Guide
  • 35. Kernel Components Tasks For example, task A and B may belong to the same data context while task A and C belong to the same program context. This does not require task B and C to share their data context. Refer to SmartDSP OS API Reference Manual for more information. Table 2.3 lists the functions available in the tasks module of the SmartDSP OS. Table 2.3 Functions Available for Tasks Flow State Name Description Kernel bring up (the user osTasksInitialize() Allocates a scheduler and application does not call then allocates tasks and these functions specifically. events objects and inserts Instead, them in the scheduler. osInitialize() calls these functions based on the parameters from os_config.h and configurations from msc81xx_config.c) Application bring up osTaskFind() Retrieves the index of an unused task. osTaskCreate() Creates a task. The task is created in the suspended state. Activate the task using osTaskActivate(). For the background task, pass a pointer to the task created using osTaskCreate() as an argument to the osStart() function. SmartDSP OS User Guide 35
  • 36. Kernel Components Tasks Table 2.3 Functions Available for Tasks (continued) Flow State Name Description Application runtime osTaskActivate() Removes the created task from the suspend state. If the task is not suspended, the function has no effect. If the task is not delayed or pending, it is moved to the ready state, and scheduler is called. If this is the highest priority ready task and it is the first in its priority queue, then it will resume or start. osTaskSuspend() Moves the task to the suspend state. osTaskDelay() Delays the running task by blocking the task for the specified number of ticks. 36 SmartDSP OS User Guide
  • 37. Kernel Components Tasks Table 2.3 Functions Available for Tasks (continued) Flow State Name Description osTaskYield() Schedules a different task in same priority or higher if available. The SmartDSP OS scheduler allows several tasks to have the same priority level. In this case, the tasks should implement cooperative scheduling to allow other tasks to execute first. The osTaskYield() function allows a task to preempt itself in favor of another specific task or next ready task of the same priority. osTaskPriorityReadyC Counts the number of ount() tasks that are ready in a specified priority. osTaskMmuDataContext Sets a data context for a Set() task. It affects the data MMU segments enabled and the DID. osTaskMmuProgContext Sets a program context Set() for a task. It affects the program MMU segments enabled and the PID. osTaskSchedulerLock( Locks the scheduler so ) that the running task cannot be replaced. osTaskSchedulerUnloc Unlocks the scheduler so k() that the running task can be replaced. Application tear down osTaskDelete() Deletes a task. Listing 2.3 shows how to find an existing task and create a new task using the osTaskFind() and osTaskCreate() functions. SmartDSP OS User Guide 37
  • 38. Kernel Components Tasks Listing 2.3 Finding and creating a task uint8_t task_stack[TASK_STACK_SIZE]; status = osTaskFind(&task_handle); OS_ASSERT_COND(status == OS_SUCCESS); os_task_init_param.task_function = F; os_task_init_param.task_name = N; os_task_init_param.stack_size = SZ; os_task_init_param.task_arg = A; os_task_init_param.task = task_handle; os_task_init_param.task_priority = OS_TASK_PRIORITY_27; os_task_init_param.private_data = D2; os_task_init_param.top_of_stack = S; /* Stack should be in a memory accessible to the task given its MMU data context */ status = osTaskCreate(&os_task_init_param); OS_ASSERT_COND(status == OS_SUCCESS); Listing 2.4 shows how to activate and suspend a task using the osTaskActivate() and osTaskSuspend() functions. Listing 2.4 Activating and suspending a task status = osTaskActivate(task_handle); OS_ASSERT_COND(status == OS_SUCCESS); status = osTaskSuspend(task_handle); OS_ASSERT_COND(status == OS_SUCCESS); Use the source code shown in Listing 2.5 to verify the task suspension. The source code verifies the task status and deletes the task (using the osTaskDelete() function) if the task is suspended. If the task is not suspended, the source code delays the task using the osTaskDelay() function. Listing 2.5 Verifying task suspension if (osTaskStatusGet(task_handle) & OS_TASK_SUSPEND) { status = osTaskDelete(task_handle); //Deleting the task OS_ASSERT_COND(status == OS_SUCCESS); } status = osTaskDelay(DELAY_TIME); //Delaying the task 38 SmartDSP OS User Guide
  • 39. Kernel Components Tasks OS_ASSERT_COND(status == OS_SUCCESS); Task States A task exists in one of these states: • Ready • Running • Blocked Figure 2.2 shows how a task transitions from one state to another. Figure 2.2 Task States A task changes its state from one to another when: • A task that is ready to run is in a READY state. • A ready to run task becomes the highest priority task and starts running, its state changes from READY to RUNNING. • A higher priority task becomes READY and preempts the current task; the currently running task state changes from RUNNING to READY. • Another higher priority task suspends a READY task; the suspended task state changes from READY to BLOCKED. • The task suspends or delays itself; the task state changes from RUNNING to BLOCKED. • A blocked task gets activated by another task, its delay expires, or a waited event occurs; the task state changes from BLOCKED to READY. SmartDSP OS User Guide 39
  • 40. Kernel Components Tasks • A task, by default, is created in a BLOCKED state. Figure 2.3 shows how a task state changes from one to another. In this figure, the arrows represent the SWI activation by HWI and stars represent events, which may or may not immediately trigger their HWI. An idle task is running. A HWI with priority 0 activates a SWI with priority 6. The SWI (Priority 6) posts the task on the semaphore, which makes the task move from pending to READY state. The task is not yet activated because SWI (Priority 6) and SWI (Priority 7) are still running in the system. The READY task becomes active only when the higher priority event or HWI or SWI finishes execution. Once all the higher priority events finish executing, the scheduler is called and SWI returns back to the interrupt dispatcher. This moves the task from READY to RUNNING state because it is the highest priority task in the system now. Figure 2.3 Task States Transition Background Task The SmartDSP OS kernel requires a task in the background so the system always has at least one task running. The last step of OS initialization activates the background task with the lowest priority. You do not need to explicitly find or create the background task; it is created by the operating system. The background task function pointer is passed as an argument to the osStart() function. The background task uses system MMU settings (wherever supported). MMU has system data settings and system program settings. The background task should not return. An application can override the default stack size for the background task in the os_config.h file using this definition: 40 SmartDSP OS User Guide
  • 41. Kernel Components Tasks #define OS_BACKGROUND_STACK_SIZE <size> NOTE An application cannot block, suspend, or delete the background task at any stage during execution. SmartDSP OS User Guide 41
  • 42. Kernel Components Spinlocks Spinlocks A spinlock is a binary lock which the currently running program waits to become available before continuing the code execution flow. In the SmartDSP OS kernel, spinlocks protect the critical data or code among multiple cores. In addition, spinlocks can be used to synchronize the tasks executing on multiple cores. The spinlock uses atomic test-and-set operations (bmtset.w) for synchronization. In the SmartDSP OS kernel, a spinlock either: • protects the critical sections from access by other cores and Interrupt Service Routines (ISR) running on the same core, or • protects the critical section from access by other cores, but not from access by ISRs running on the same core. NOTE bmtset.w is StarCore specific. Refer to SC3850 DSP Core Reference Manual for more information about bmtset.w. The data is guarded locally on the core among tasks by enabling/disabling interrupts or by using osHwiSwiftDisable()/osHwiSwiftEnable() functions. Spinlocks should be used only when data is shared between cores. A spinlock in the SmartDSP OS kernel is 32 bits in memory, non-cacheable, and in memory which supports atomic operations, such as, M2 in MSC814x architecture and M3 in MSC815x architecture. NOTE Do not use the same spinlock on the same core in different priorities (HWI, SWI, and/or tasks) without closing interrupts. A deadlock may occur. The following functions are used for acquiring spinlocks: • osSpinLockGet()— Acquires the spinlock. This is a blocking operation. Use this function with caution because of the possibility of deadlock. • osSpinLockIrqGet()— Disables interrupts and then acquires the spinlock. This is a blocking operation. • osSpinLockTryGet()— Tries to acquire the given spinlock. Returns whether or not the spinlock is acquired. This is a non-blocking operation. The following functions are used for releasing spinlocks: • osSpinLockRelease()— Releases the spinlock. • osSpinLockIrqRelease()— Releases the spinlock and then enables interrupts. 42 SmartDSP OS User Guide
  • 43. Kernel Components Memory Manager NOTE The osSpinLockGet() and osSpinLockRelease() calls do not disable interrupts, which can lead to deadlocks if an ISR tries to access the critical section. Also, performance degradation can occur if one core gets the spinlock and jumps to an ISR from within the critical section, leaving the other cores waiting for the spinlock while the ISR is being served. To use a fake spinlock, define its address as OS_GUARD_DISABLE. OS_GUARD_DISABLE is a SmartDSP OS defined macro that when assigned to the spinlock, indicates that no action will take place on the spinlock and the core will not execute any syncio (blocking) instructions. The following source code shows how to use the OS_GUARD_DISABLE macro: uint32_t dummy_spinlock_addr = OS_GUARD_DISABLE; /* Won't take spinlock. Won't execute syncio */ osSpinLockGet((volatile uint32_t *)dummy_spinlock_addr); Memory Manager The memory manager component of the SmartDSP OS kernel module handles memory allocation and buffer management. The memory manager allocates memory blocks dynamically and frees them when they are no longer in use. The SmartDSP OS memory manager enables efficient allocation, retrieval, and release of memory blocks of known size and alignment without memory fragmentation. Memory management in SmartDSP OS is split into two stages, initialization and runtime. All initialization functions can be called at runtime and all runtime functions can be called at initialization. The SmartDSP OS default linker file provides a symmetrical view into the memory of each core, which: • allows easier transition from single to multicore. • allows easier reassignment of tasks from one core to another. For example, if a core starts and runs tasks A, B, and C and finds that it does not have the necessary bandwidth to create task D, the other core can create the task D and run it. However, it is not possible for one core to run a task created by another core. • allows easier debugging of memory-related bugs. • comes at the cost of aligning all cores to the core with the heaviest requirements. The SmartDSP OS partitions each shared physical memory into two main fragments: • Local, which is further fragmented based on the number of cores (Figure 2.4) • Shared (Figure 2.5 and Figure 2.6) SmartDSP OS User Guide 43
  • 44. Kernel Components Memory Manager Figure 2.4 Local Memory Figure 2.4, Figure 2.5, and Figure 2.6 shows the MSC814x default memory map. Figure 2.5 Shared M3 Memory 44 SmartDSP OS User Guide
  • 45. Kernel Components Memory Manager Figure 2.6 Shared DDR Memory Memory Allocation The memory manager supports the allocation of memory from different memory sections using the osMalloc() function. Note that the SmartDSP OS does not support an equivalent osFree() function and therefore allocated memory is never really released. In order to see how much memory is being consumed, you should modify the value of the flag OS_PRINT_MALLOC_STATISTICS in includecommonos_mem.h and recompile. This will cause each call to osMalloc() to produce on to the output console: "Core <core_num>. File: <file_name>. Line: <line_num>. osMalloc(<size>, <heap_name>)n" You can redirect the output to a file using os_malloc_file_handle = fopen(w, <user_file_name>); osMalloc() can be called at any time to allocate a slab on continuous (virtual) memory from a predefined heap. osMalloc() heaps are either shared or private, which are described as: • Shared heaps are described as an array, g_mem_heap_shared[], in the mscxxxx_shared_mem.c file • Private heaps are described as an array, g_mem_heap_local[], in the mscxxxx_init.c file A heap (os_mem_heap_t) is defined as having three distinctive characteristics: • Base address • Size SmartDSP OS User Guide 45
  • 46. Kernel Components Memory Manager • Type (os_mem_type) Listing 2.6 shows an example of a heap.structure. Listing 2.6 Structure of a heap typedef struct { volatile uint32_t* mem_start; volatile uint32_t* mem_size; volatile uint32_t* mem_type; } os_mem_heap_t; A SmartDSP OS application can add heaps into the arrays that can be allocated at compile time. Each heap has a distinctive enumeration. The SmartDSP OS defined heaps are enumerated in os_mem_type. The SmartDSP heap enumeration is split into the following three fields, each having a bit mask: • The valid field verifies the validity of a heap • The flags field specifies the characteristics (for example, shared, or cacheable) of the heap • The memory type field specifies the type of memory (for example, M1, M2, M3, DDR) in which the heap resides All heaps provided by SmartDSP will have OS_SMARTDSP_HEAP as one of the flags defined in their enumeration. This flag signifies that the heap is defined by the SmartDSP OS. The following source code snippet shows an example of a heap enumeration: OS_MEM_DDR0_LOCAL = (OS_VALID_NUM | OS_SMARTDSP_HEAP | OS_MEM_CACHEABLE_TYPE | OS_MEM_DDR0_TYPE), All other flags are assumed to be valid in any user-defined heap identifier. The main header file for memory management is os_mem.h. The memory types, flags, and validity checks are defined in os_mem.h as shown in Listing 2.7: Listing 2.7 Memory type, flag, valid defined in os_mem.h // MASK to extract memory type #define OS_VALID_NUM_MASK 0xFFF00000 /**< SmartDSP validity check number is encoded here */ #define OS_MEM_FLAGS_MASK 0x000FF000 /**< Memory flags should be encoded in these bits */ #define OS_MEM_TYPE_MASK 0x0000001F /**< Memory type should be encoded in these bits */ 46 SmartDSP OS User Guide
  • 47. Kernel Components Memory Manager #define OS_VALID_NUM 0xEC900000 /**< Used by SmartDSP code to ensure that this is a valid heap */ // Memory flags #define OS_SMARTDSP_HEAP 0x00080000 /**< Bit signifying that the heap is defined by SmartDSP */ #define OS_MEM_CACHEABLE_TYPE 0x00040000 /**< Bit signifying that the heap is cacheable */ #define OS_MEM_SHARED_TYPE 0x00020000 /**< Bit signifying that the heap is shared */ // Memory types #define OS_MEM_M1_TYPE 0x00000001 /**< Heap in M1 memory */ #define OS_MEM_M2_TYPE 0x00000002 /**< Heap in M2 memory */ #define OS_MEM_M3_TYPE 0x00000003 /**< Heap in M3 memory */ #define OS_MEM_DDR0_TYPE 0x00000004 /**< Heap in DDR0 memory */ #define OS_MEM_DDR1_TYPE 0x00000005 /**< Heap in DDR1 memory */ #define OS_MEM_QE_PRAM_TYPE 0x00000006 /**< Heap in QE PRAM memory */ #define OS_MEM_MAPLE_PRAM_TYPE 0x00000007 /**< Heap in MAPLE PRAM memory */ NOTE To prevent a user-defined heap identifier from clashing with a SmartDSP identifier; do not define the OS_SMARTDSP_HEAP flag as part of the heap identifier. Buffer Management The SmartDSP OS memory manager manages a pool of buffers, which can either be allocated statically during compilation or dynamically using osMalloc().The size of the memory manager is dependant on the number of buffers in the managed buffer pool. An application should use the MEM_PART_SIZE(<num buffers>) macro to define the memory size to allocate for the memory manager. The number of buffers to be managed by the memory manager is passed as an argument to the macro. An application can also use the MEM_PART_DATA_SIZE(<num buffers>,<buffer size>,<alignment>) macro for setting aside the buffer pool. For example, to manage 100 buffers that are dynamically allocated each having a size of 73 bytes, with an alignment of 8 bytes, your application may call osMalloc() function as: osMalloc(MEM_PART_DATA_SIZE(100, 73, ALIGNED_8_BYTES), OS_MEM_LOCAL) SmartDSP OS User Guide 47
  • 48. Kernel Components Memory Manager to allocate the buffer pool. Also, the macro MEM_PART_SIZE will take 100 as the argument while creating memory manager. Memory managers can manage shared as well as private buffer pools. Listing 2.8 displays the source code that an application uses for buffer management. The source code uses the function, osMemPartCreate(), which initializes a memory structure for aligned and fixed-size blocks. Listing 2.8 Initializing memory structure for aligned and fixed-size blocks os_mem_part_t * osMemPartCreate(uint32_t block_size, uint32_t num_of_blocks, uint8_t *data_address, uint32_t alignment, uint16_t buffer_offset, os_mem_part_t *mem_part #if (OS_MULTICORE == 1) ,bool shared #endif ); The osMemPartCreate() function contains the following parameters: • block_size — Specifies the size of the allocatable block. • num_of_blocks — Specifies the maximum number of allocatable blocks. • data_address — Specifies the address of the contiguous block of buffers to manage. The user application may use the MEM_PART_DATA_SIZE() macro to set aside this memory. • alignment — Specifies how the blocks are aligned (in bytes). • buffer_offset — Specifies an offset in the buffer to be reserved for Low Level Driver (LLD) or application use. • mem_part — Specifies the address of the memory manager space to initialize. The user application may use the MEM_PART_SIZE() macro to set aside this memory. • shared — Specifies a flag that indicates whether this memory partition is shared among cores or not. It receives a value of TRUE or FALSE. Listing 2.9 shows an example of how to allocate memory statically and then call the osMemPartCreate() function to manage the memory. Listing 2.9 Allocating memory statically os_mem_part_t *jobs_pool; uint8_t jobs_space[MEM_PART_DATA_SIZE(NUM_JOBS_PER_CORE, sizeof(app_type_job), ALIGNED_4_BYTES)]; uint8_t jobs_mem_manager[MEM_PART_SIZE(NUM_JOBS_PER_CORE)]; jobs_pool= 48 SmartDSP OS User Guide
  • 49. Kernel Components Memory Manager osMemPartCreate(ALIGN_SIZE(sizeof(app_type_job),ALIGNED_4_BYTES), NUM_JOBS_PER_CORE, jobs_space, ALIGNED_4_BYTES, OFFSET_0_BYTES, (os_mem_part_t *)&jobs_mem_manager, FALSE); In the above source code example, jobs_pool is the memory manager that manages the buffer pool. jobs_space is the actual buffer structure that is to be managed. It stores the number of bytes that are to be managed by the memory manager. It can be initialized using the MEM_PART_DATA_SIZE macro as an argument, which contains the following three arguments: • Number of buffers — (NUM_JOBS_PER_CORE) • Size of buffers — (sizeof(app_type_job)) • Alignment of buffers — ALIGNED_4_BYTES jobs_mem_manager manages job space itself using jobs_pool. It is a private partition and not shared. It can be initialized using the MEM_PART_SIZE(NUM_JOBS_PER_CORE) macro, which contains the NUM_JOBS_PER_CORE argument. Based on this memory allocation, the osMemPartCreate() function is called where: • ALIGN_SIZE(sizeof(app_type_job), ALIGNED_4_BYTES) — Indicates that memory manager manages the memory blocks where the size of each block is the size of the structure aligned. The aligned structure is defined in os_mem.h. The alignment of the structure is four bytes. • NUM_JOBS_PER_CORE — Indicates the number of blocks that the memory manager will manage. • jobs_space — Indicates the address of the blocks. • jobs_mem_manager — Indicates the memory manager containing the number of jobs per core to be managed. • FALSE — Indicates that the memory partition is not shared. The osMemPartCreate() function returns a pointer to the initialized memory managing structure (os_mem_part_t). Use these functions to retrieve buffers: • void * osMemBlockGet(os_mem_part_t *mem_part) — Retrieves a block form the memory manager. • void * osMemBlockUnsafeGet(os_mem_part_t *mem_part) — Retrieves a block form the memory manager (unsafe version). Use this function SmartDSP OS User Guide 49
  • 50. Kernel Components Memory Management Unit (MMU) when you are sure that the memory manager cannot be accessed from any other source. • void * osMemBlockSyncGet(os_mem_part_t *mem_part) — Retrieves a block from the memory manager (multicore safe version). Use these functions to free buffers: • void osMemBlockFree(os_mem_part_t *mem_part, void *addr) — Releases a block back to the memory manager. • void osMemBlockUnsafeFree(os_mem_part_t *mem_part, void *addr) — Releases a block back to the memory manager (unsafe version). Use this function when you are sure that the memory manager cannot be accessed from any other source. • void osMemBlockSyncFree(os_mem_part_t *mem_part, void *addr) — Releases a block back to the memory manager (multicore safe version). Memory Management Unit (MMU) An MMU is a hardware component that is used to extend memory addressing capabilities and control access to Random Access Memory (RAM) and entire SoC. The MMU translates the logical addresses into physical memory addresses. An MMU is used to map and protect memory segments on each core. The SmartDSP OS for MSC814x and later platforms provides MMU support, which: • supplies hardware memory protection for instruction and data accesses. • supports the bridging of two privilege levels (user and supervisor). • implements high-speed address translations from virtual to physical address. • provides cache and bus control for advanced memory management. • supports software coherency with cache sweep operations that invalidate, flush, and synchronize. For address translation, there is a software model in which the source code is written in virtual addresses that are translated to physical addresses before issuing them to memory. The SmartDSP OS distinguishes between program and data attributes of the MMU. The SmartDSP OS extensively uses the MMU for building the same virtual memory map that includes both local and shared memory for each core. Shared memory is accessible by all the cores and local regions are accessible by only one core. The MMU makes it easier to port single core applications by creating an identical single core alike virtual map. In this way, every core owns its local memory with explicitly defined regions for shared memory. 50 SmartDSP OS User Guide
  • 51. Kernel Components Memory Management Unit (MMU) MMU Features As part of the DSP Subsystem, an MMU: • provides memory region support as follows: – Provides read allowed/not allowed for both supervisor and user levels in the program memory region – Provides read/write allowed/not allowed for both supervisor and user levels in the data memory region • defines address translation for each data/program memory region so that a virtual memory region can be allocated to a valid physical memory space. • stores the program task ID and data task ID for multi-task mechanism. • handles access error detection with support for non-mapped memory access and misaligned memory access. • presents two abstractions, Segment and Context, in SmartDSP. • defines cache policy on each segment. MMU Segment An MMU segment defines a memory region and its attributes, protection, and address translation. Each MMU segment is either a program or data but not both. Segment programming is predefined in the Linker Command File (LCF), during runtime, or a combination of both. Refer to the relevant DSP subsystem Reference Manual for MMU alignment restrictions. An MMU segment includes: • memory translation • permissions • cache properties • memory properties NOTE The SmartDSP OS collectively refers to data and program segments as system segments. MMU Segment Abstraction MMU segment abstraction includes cache attributes and provides a single translation from virtual to physical addresses (see Figure 2.7). SmartDSP OS User Guide 51
  • 52. Kernel Components Memory Management Unit (MMU) Figure 2.7 MMU Segment Both system and user segments are available in the SmartDSP OS. System segments are included in the SmartDSP OS application contexts. User segments are only included through a specific context. Multiple contexts can include the same user segment. MMU Segment Creation In the initialization phase, the SmartDSP OS creates MMU segments according to the executable, using an environment-specific format. In CodeWarrior IDE, for example, an application uses the Linker Command File (LCF) for segment definition and attribute and ID associations. In this case, the SmartDSP OS enables all system segments and adds them to the system context. The SmartDSP OS adds user segments to the user contexts according to the context definition. An application creates a MMU segment explicitly using the API functions, osMmuProgSegmentCreate() and osMmuDataSegmentCreate(). These functions create MMU segments according to the given parameters. After creating the segment, the segment can be added to any context using the osMmuDataContextSegmentsAdd() or osMmuProgContextSegmentsAdd() functions. In such cases, the segment is active when the context is active. It is also possible to enable the segment using the osMmuDataContextActivate() function. NOTE If a MMU segment is added to the current context, the SmartDSP OS activates it upon the next activation of the context. An example of the activation of an MMU segment is shown in Listing 2.10. Listing 2.10 Activating a MMU segment status = osMmuDataSegmentFind(&data_segment); if (status != OS_SUCCESS) OS_ASSERT; status = osMmuDataSegmentCreate(data_segment,(void*)VIRT_BASE1, (void*)PHYS_BASE1, SEGM_SIZE, MMU_DATA_DEF_SYSTEM, 52 SmartDSP OS User Guide
  • 53. Kernel Components Memory Management Unit (MMU) NULL); if (status != OS_SUCCESS) OS_ASSERT; status = osMmuDataSegmentEnable(data_segment, TRUE); if (status != OS_SUCCESS) OS_ASSERT; In the above example, the application activates a segment rather than adding it to a given context. The segment is active only until the next context switch. MMU Context A SmartDSP OS MMU context is a group of segments that can be associated with a task. An MMU context defines a subset of software context. An MMU context defines a set of active segments as well as an ID. This ID is the PID/ DID of all tasks belonging to the context. An MMU context is shown in Figure 2.8. Figure 2.8 MMU Context There are two types of contexts. A program context is a set containing a unique program ID and a subset of defined program segment descriptors. A data context is a set with a unique data ID and a subset of defined data segment descriptors. Each task belongs to a single data context and program context. By default, tasks belong to system contexts but for segment mapping, they maintain their own unique PID/DID. A task belonging to a context, which has been associated to the task during runtime, has data ID at that context and the set of segments enabled in that context. Tasks do not need to belong to the same context for data and program. Each task is created using the MMU segment of the system context. The system PID/DID is 1. MMU Context Abstraction The SmartDSP OS preserves data and program contexts on each HWI and SWI. System context is enabled on each task and HWI/SWI interrupt. The system contexts begin by including segments for which MMU_PROG_DEF_SYSTEM or MMU_DATA_DEF_SYSTEM was set in the segment attributes in LCF. SmartDSP OS User Guide 53
  • 54. Kernel Components Memory Management Unit (MMU) User context normally includes all system context segments because they must be enabled continuously. However, in some cases, system context segments are removed from the user context. System context usually only includes system segments but it can also include user segments. NOTE Changes to the system contexts are reflected in all contexts. MMU Context Creation The SmartDSP OS creates all MMU contexts using information from LCF. An application creates a MMU context explicitly by using osMmuDataContextFind() and osMmuProgContextFind(). These functions send a pointer to the first available context and set a supplied ID to the context. An application modifies the MMU context by adding new segments using osMmuProgContextSegmentsAdd() or osMmuDataContextSegmentsAdd(). The osMmuProgSystemContextSegmentAdd() function adds a given segment to the system program context and this reflects in all program contexts. You can add a segment to the system context only by using the osMmuDataContextFind() function with the parameter, OS_MMU_SYSTEM_CONTEXT. You can associate an MMU context with a SWI by calling the osSwiMmuDataContextSet() function. This allows SmartDSP OS to activate the system context when a SWI starts and then replace the system context with the context you specify. An application enables the context by calling the osMmuDataContextActivate() function, which has the same effect as a task switch. An MMU context creation is shown in Figure 2.9. Figure 2.9 MMU Context Creation 54 SmartDSP OS User Guide
  • 55. Kernel Components Memory Management Unit (MMU) MMU Configuration The main header file of the SmartDSP OS MMU is includecommonos_mmu.h. The number of data and program contexts have default values which can be overridden in os_config.h in the following definitions: • #define MMU_DATA_CONTEXT_NUM <num> • #define MMU_PROG_CONTEXT_NUM <num> An array of data and program contexts will be allocated from the OS_MEM_LOCAL heap. The user application will therefore face the penalty in terms of memory footprints for defining an improper number of contexts or for defining too many contexts that override the default value. Tasks and contexts share the reserved number of IDs that are defined in the MMU (platform specific), which is 1+num_tasks+num_contexts<=max_ID. MMU segments (both data and program) that are not defined in the LCF can be added during initialization or runtime using the following functions: • osMmuDataSegmentFind() • osMmuDataSegmentCreate() • osMmuDataSegmentEnable() • osMmuProgSegmentFind() • osMmuProgSegmentCreate() • osMmuProgSegmentEnable() Once an MMU segment is created, it can be added to a MMU context using the following functions: • osMmuDataContextSegmentsAdd() • osMmuProgContextSegmentsAdd() • osMmuDataSystemContextSegmentAdd() • osMmuProgSystemContextSegmentAdd() MMU Segments can also be removed from MMU contexts using the following functions: • osMmuDataContextSegmentRemove() • osMmuProgContextSegmentRemove() • osMmuDataSystemContextSegmentRemove() • osMmuProgSystemContextSegmentRemove() To perform address translation, an application can call the following functions: • osMmuProgVirtToPhys() • osMmuDataVirtToPhys() SmartDSP OS User Guide 55
  • 56. Kernel Components Memory Management Unit (MMU) To perform address validation, an application can call the following functions: • osMmuProgVirtProbe() • osMmuDataVirtProbe() MMU Exceptions MMU exceptions are non-maskable and precise. The SmartDSP OS has default handlers for program and data MMU exceptions, which can perform the following tasks: • Detect the context from which the error occurred • Detect the root cause of the error and clear the interrupt in the MMU • Call a user-defined debug hook if enabled • Stop the core An application can override these exceptions by calling osHwiDelete() followed by osHwiCreate() for OS_INT_DMMUAE (data MMU) and/or OS_INT_IMMUAE (instruction MMU). Use the function, osMmuDataErrorDetect() or osMmuProgErrorDetect() to clear the interrupt and return one of the root causes of the exception, as shown: • status = osMmuDataErrorDetect(struct os_mmu_error *) • status = osMmuProgErrorDetect(struct os_mmu_error *) An example of returning the cause of an MMU error is shown in Listing 2.11. Listing 2.11 Returning the cause of MMU error struct os_mmu_error { uint32_t error_address; //violation address uint32_t error_pc; //program counter that caused exception uint32_t rw_access; //read is 0, write is 1 uint32_t privilege_level; //user is 0, supervisor is 1 uint32_t access_width; //Access Violation Width }; There are two non-contradicting procedures to debug a MMU error. First procedure: 1. Look at the root cause of the error using status of the os_mmu_error structure. 2. View memory as program at the err.error_pc to look at the program counter where error happened. 3. See what you are doing. 4. Compare with what you meant to have been doing. 56 SmartDSP OS User Guide
  • 57. Kernel Components Caches 5. See where the error originated. Second procedure: 1. Step out of the handler. 2. Step through the interrupt dispatcher (_osHwiPreciseDispatcher). 3. Step back into the code. 4. Look at the stack and see where the error originated. Caches A cache is a high-speed memory area where the information is stored temporarily for fast access. The information retrieved from main memory is copied to the cache. The CPU fetches the information from the cache instead of main memory. This reduces the access time and enhances memory performance. The SmartDSP OS supports different types and hierarchies of cache memories. Level 1 or L1 cache is an internal cache that is generally very small and private. Level 2 or L2 cache is the secondary cache, also referred to as external cache. It is larger and slower, compared to L1 cache. The SmartDSP OS kernel has extensive cache functionality for the MSC814x and MSC815x platforms. The SoC caches supported by StarCore processors are shown in Table 2.4. Table 2.4 StarCore SoC Caches Processor Cache MSC8101 No cache MSC812x private L1-I$ MSC814x private L1-I$/D$, shared L2-I$ MSC815x private L1-I$/D$, private unified L2 NOTE For MSC812x, the SmartDSP OS only enables or disables the cache. Cache Sweep Commands Each MMU segment has specific cache characteristics defined during segment creation or in the LCF. An application utilizes cache sweep commands, which are a mechanism to SmartDSP OS User Guide 57
  • 58. Kernel Components Caches support platform cache coherency. This mechanism enables data sweeping (such as invalidate, flush, and synchronize) of a specific range of addresses that are programmed in the cache registers. The SmartDSP OS supports two types of sweep commands: • Synchronous (or blocking) — The sweep command is accomplished after return. The synchronous function, osCacheDataSweep() performs the requested action on data cache and polls until the operation is finished. • Asynchronous (or non-blocking) — The sweep operation can be in process after return. The asynchronous function, osCacheDataSweepAsync() performs the requested action on data cache and returns. Both the synchronous and asynchronous functions initially check whether previous commands have been completed or not. An application can check the status of the sweep operation by using the osCacheDataInProgressSweep() function. Configuration of Caches in SmartDSP OS The main header file of the SmartDSP OS caches is includecommonos_cache.h. The SmartDSP OS distinguishes between the various caches in the system and provides an API for each supported type. At initialization, caches are configured based on the following definitions in the os_config.h file: • #define DCACHE_ENABLE ON • #define ICACHE_ENABLE OFF • #define L2CACHE_ENABLE ON //MSC815x only • #define OS_L2_CACHE_SIZE ((uint32_t)&_L2_cache_size) // in MSC815x only for specifying how much shared M2 and L2 be used as core M2 memory or as L2 cache There are two types of hardware-supported cache operations: Global and By Address. The function, osCacheL2ProgSweepGlobal() sweeps the L2 program globally on the entire cache. The function, osCacheProgSweep(), performs a sweep operation by address on program cache. The L1 caches in MSC814x and MSC815x platforms work with virtual addresses. L2 caches do not work with virtual addresses. Non-global L1 cache operations require a task ID. On shared segments, an application should use MMU_SHARED_PID. Non-global cache operations must specify addresses with the granularity of cache lines. A cache line contains multiple Valid Bit Resolution (VBR) chunks of memory. Although cache operations for hardware can operate on VBR-by-VBR basis, the minimum granularity for L1 cache operations is the cache line. This means that cache operations are performed on all VBR in the cache line. Therefore, the SmartDSP OS enforces the granularity of cache lines while calling the cache sweep operation. 58 SmartDSP OS User Guide
  • 59. Kernel Components Queues The SmartDSP OS provides the ARCH_CACHE_LINE_SIZE macro for allowing easy alignment to the L1 cache line size. The following macros are available for aligning cache operations to line size: • #define CACHE_OP_LOW_ADDR (VIRT_BASE, GRANULARITY) • #define CACHE_OP_HIGH_ADDR (VIRT_BASE, SIZE, GRANULARITY) The alignment of cache operations to cache line size is shown in Listing 2.12. Listing 2.12 Alignment of cache operations to the cache line size long read_from_maple(void* addr, void* data, uint32_t size, uint32_t dev_id) { os_status status; uint32_t cache_addr_lo,cache_addr_hi; cache_addr_lo=CACHE_OP_LOW_ADDR(data, ARCH_CACHE_LINE_SIZE); cache_addr_hi=CACHE_OP_HIGH_ADDR(data, size,ARCH_CACHE_LINE_SIZE); osCacheDataSweep((void*)cache_addr_lo, (void*)cache_addr_hi, MMU_SHARED_PID, CACHE_FLUSH); return (long)size; } Queues A queue is a linear data structure which contains a collection of entities. The entities are added at the rear end and removed from the front end. A SmartDSP OS queue implements a First in First Out (FIFO) algorithm. Queues in SmartDSP OS are used as a basic component in various abstraction layers and utilities. The queues are private per core and they queue data that is four bytes in size (uint32_t). A queue can be either specific to a core, or can be shared by all cores. All queues are protected from access by the same core. There is a special version of queues called multiple queues, which queue different sizes of data. The size is determined while creating the queue. Currently, the queue component supports the queuing of 32 bit values only. In the configuration file, an application can define the maximum number of both regular queues and shared queues allowed by the system. SmartDSP OS User Guide 59
  • 60. Kernel Components Queues Queues send one or more messages to a task. A task can use a queue to post messages to software or hardware interrupts. A task or interrupt handler can place a message in the form of a pointer in the queue as well as receive messages from the queue. The SmartDSP OS provides two kinds of queue, shared and private. Shared queues use spinlocks and are allocated using OS_MEM_SHARED. Private queues are allocated using OS_MEM_LOCAL and override the spinlock mechanism using OS_GUARD_DISABLE. Queue runtime API may be either safe or unsafe, which are equally legal for both shared and private queues. The functions in the safe queue runtime API are protected with osSpinLockIrqXxx(). No protection is provided in the unsafe queue runtime API. An application defines the number of queues in the os_config.h file as: #define OS_TOTAL_NUM_OF_QUEUES 48 #define OS_TOTAL_NUM_OF_SHARED_QUEUES 0 Perform the following steps to create a queue. You should perform these steps in your application's initialization source code because these steps involve memory allocations. 1. Get a handle to a queue by calling osQueueFind(), specifying whether you need to find a shared queue or a regular queue. 2. Call osQueueCreate() after you find a valid queue handle. This function initializes the queue with the required size. 3. Use osQueueEnqueue() to start inserting items into the queue, and osQueueDequeue() to remove items. The functions available in the queue module of the SmartDSP OS are listed in Table 2.5. Table 2.5 Functions Available for Queues Flow State Name Description Kernel bring up (the user osQueueInitialize Initializes the OS application does not call these () queues. functions specifically. Instead, osInitialize() calls these functions based on the parameters from os_config.h and configurations from msc81xx_config.c) Application bring up osQueueFind() Finds the first available queue number. osQueueCreate() or Prepares a queue for osQueueCreateMult operation. iple() 60 SmartDSP OS User Guide
  • 61. Kernel Components Queues Table 2.5 Functions Available for Queues (continued) Flow State Name Description Application runtime osQueueEnqueue() or Inserts a value into a osQueueEnqueueMul queue. tiple() osQueueUnsafeEnqu Inserts a value to a eue() or queue (unsafe version). osQueueUnsafeEnqu Use this function when a eueMultiple() queue object cannot be accessed from any other source. osQueueHeadEnqueu Inserts a value into the e() front of a queue. osQueueUnsafeHead Inserts a value into the Enqueue() front of a queue (unsafe version). Use this function when a queue object cannot be accessed from any other source. osQueueDequeue() or Removes the first value osQueueDequeueMul from a queue. tiple() osQueueUnsafeDequ Removes the first value eue() or from a queue. Use this osQueueUnsafeDequ function when a queue eueMultiple() object cannot be accessed from any other source. osQueueTailDequeu Removes the last value e() from a queue. osQueueUnsafeTail Removes the last value Dequeue() from a queue. Use this function when a queue object cannot be accessed from any other source. SmartDSP OS User Guide 61
  • 62. Kernel Components Intercore Messaging Table 2.5 Functions Available for Queues (continued) Flow State Name Description osQueueStatus() Queries the status of a queue, such as OS_QUEUE_EMPTY or OS_QUEUE_FULL. osQueueUnsafeStat Queries the status of a us() queue, such as OS_QUEUE_EMPTY or OS_QUEUE_FULL. Use this function when a queue object cannot be accessed from any other source. osQueueReset() or Empties the given osQueueResetUnsaf queue e() osQueuePeek() Queries the first value in the queue without removing it. Application tear down osQueueDelete() Deletes the given queue from the system. All queues, including unshared queues, are protected from access by the same core. In a multicore system, an application can request the queue to be a shared queue. The shared queue object resides in the shared memory and is protected from access by other cores. Intercore Messaging In a multicore environment, intercore messaging allows applications running on different cores to communicate with each other. The intercore messaging component of the SmartDSP OS module allows communication between applications through messages by associating interrupts with handlers written in C or assembly language. Intercore messages in the SmartDSP OS are point-to-point. An application can post an intercore message at any time. Reception of intercore messaging is possible only after creating the message or listening to the message. Intercore messaging in the SmartDSP OS may be either synchronous or asynchronous. Synchronous intercore messaging uses the following process: 62 SmartDSP OS User Guide
  • 63. Kernel Components Intercore Messaging 1. The sending core takes a mailbox spinlock. 2. The sending core writes data to a mailbox. 3. The sending core interrupts a recipient. 4. The recipient is interrupted. Mailbox number is returned as an interrupt handler argument (os_hwi_arg). 5. The recipient reads mailbox data. 6. The recipient frees the spinlock. Asynchronous intercore messaging uses the following process: 1. Data is predefined during initialization and set as an interrupt handler argument (os_hwi_arg). 2. The sending core interrupts the recipient. 3. The recipient is interrupted. The VIRQ were used for intercore messaging in MSC812x and MSC814x. In MSC815x, the interrupt mesh between cores is used for intercore messaging. The kernel initializes the inter-core messaging module of the SmartDSP OS using the osMessageInitialize() function. Configuration of Intercore Messaging The main header file of the SmartDSP OS intercore messages is: includecommonos_message.h. Intercore messaging is only enabled where OS_MULTICORE is predefined as 1 (that is, not enabled in MSC8101). The maximum number of supported messages in the architecture is defined in smartdsp_os_device.h as: #define MSC814X_MAX_NUM_OF_MESSAGES 4 #define MSC815X_MAX_NUM_OF_MESSAGES 2 The number of intercore messages is defined by an application in os_config.h, as: #define OS_TOTAL_NUM_OF_INTERCORE_MESSAGES 1 NOTE The number of messages should be interpreted as the number of point-to-point messages; that is, multiplied by the number of cores. An application defines the maximum number of intercore messages allowed by the system in the configuration file. Intercore messaging mailboxes are allocated from the OS_SHARED_MEM heap during initialization. Because intercore messaging uses spinlocks, a requirement is placed on the physical memory in which this heap is linked. Refer to SmartDSP OS API Reference Manual for more information. Functions available for intercore messaging are listed in Table 2.6. SmartDSP OS User Guide 63
  • 64. Kernel Components Intercore Messaging Table 2.6 Functions Available for Intercore Messaging Flow State Name Description Kernel bring up (the user osMessageInitiali Initializes the multicore application does not call these ze() synchronization functions specifically. Instead, module. osInitialize() calls these functions based on the parameters from os_config.h and configurations from msc81xx_config.c) Application bring up osMessageFind() Finds the first available inter-core message number. osMessageCreate() Installs an intercore or message handler for the osMessageCreateAs calling core to start the ync() communication. When a specific message arrives, this function enables the calling core to be notified. The calling core can then handle the message. 64 SmartDSP OS User Guide
  • 65. Kernel Components Intercore Messaging Table 2.6 Functions Available for Intercore Messaging (continued) Flow State Name Description Application runtime osMessagePost() or Posts the given osMessagePostIrq( message number or ID ) or with the given data to osMessagePostAsyn the destination core. c() This function performs the following tasks: • Posts a virtual interrupt to the destination core and associates a message with this interrupt • Gets a message ID and pass it to handler as parameter While the message is posted, no other core can post the same message number to the same core. As a result, the data is safe until the destination core fetches the message. osMessageGet() Retrieves the data from a message (with the message ID) that was posted to the calling core. When your application receives a message, you must call osMessageGet() to dismiss the interrupt, even if you are not interested in the contents of the message. SmartDSP OS User Guide 65
  • 66. Kernel Components Intercore Message Queues Table 2.6 Functions Available for Intercore Messaging (continued) Flow State Name Description Application tear down osMessageDelete() Deletes an existing intercore message handler. The deleted message number cannot be used after it is deleted. Intercore Message Queues The intercore message queue module of the SmartDSP OS is used for inter-process communication within the same process or intercore communication which is not necessarily point-to-point. The intercore message queue uses a queue for transferring the messages or content between processes. Intercore message queues in the SmartDSP OS are point-to-multipoint. Enqueuing and de- queuing from a message queue is possible only after creating it. In all architectures, message queues use VIRQ. As a result, the number of message queues is bound only by the number of other VIRQ users, such as intercore messaging (on MSC812x/MSC814x) and RIONET (on MSC814x/MSC815x), and the number of VIRQ in the SoC. The kernel initializes the intercore message queue module of the SmartDSP OS by using the osMessageQueueInitialize() function. Configuration of Intercore Message Queues in SmartDSP OS The main header file of the SmartDSP OS intercore message queue is includecommonos_message_queue.h. Intercore message queues are allocated from the OS_SHARED_MEM heap during initialization. Intercore messaging is only enabled where OS_MULTICORE is predefined to 1; therefore it cannot be enabled in the MSC8101 platform. The number of intercore message queues is defined by an application in os_config.h as: #define OS_TOTAL_NUM_OF_MESSAGE_QUEUES 1 Refer to SmartDSP OS API Reference Manual for more information. The functions available in the intercore message queue module of the SmartDSP OS are listed in Table 2.7. 66 SmartDSP OS User Guide
  • 67. Kernel Components Intercore Message Queues Table 2.7 Functions Available for Intercore Message Queues Flow State Name Description Application bring up osMessageQueueCreat Installs an intercore e() message handler for the calling core. Then, the calling core can handle the message. Application runtime osMessageQueuePost( Posts the given message ) number with the given data to the destination core. osMessageQueueGet() Retrieves the data from a or message that was posted osMessageQueueDispa to the calling core. tcher() Note: User may call the function repetitively until the queue is empty: while(OS_ERR_Q_EMPT Y != osMessageQueueGet() ); Application tear down Not supported Intercore Options The SmartDSP OS provides various intercore options to establish communication between cores in a multicore platform. An application can use any of the following options while using intercore messaging APIs (see Figure 2.10): • Standard AMP scheduler where each core handles it's own tasks • Data flow between core using intercore messages • Master-Slave or producer-consumer using message queues SmartDSP OS User Guide 67
  • 68. Kernel Components Events Figure 2.10 Intercore Options Events An event is a kernel object that enables communication between tasks and the system. Tasks, except background task, can remain pending on events until an event is available or when a timeout occurs. An HWI, SWI, or another task can post the event to restart a blocked task. An event can also be referred as a function in the system that an HWI, SWI, or task can accept to check if it is available. Events enable signals to the blocking task to notify that the task should wake up and give some data to the event, if necessary. An event may include data; therefore, it is possible to post and receive a message from an event. Events are a ‘base class’ in the SmartDSP OS. There is no public header file for events and an application is not expected to call its functionality directly. Events cannot be shared among different cores. Events and their derivatives are private in each core. The following lists some of the scenarios of events: • Events have a list of pending tasks for the specific event. • If an event is available, the pending task is not blocked and there is no delay in its execution. • If a function in the system posts an event and a task is pending on that event then the posting function will get the pending task ID. 68 SmartDSP OS User Guide
  • 69. Kernel Components Events • If no task is pending on a posted event, it will return TASK_NULL_ID. • If an event is not available, the task gets blocked and a context switch occurs. • If a task is blocking the number of seconds it specified as timeout, it becomes ready and the pending function returns OS_ERR_EVENT_QUEUE_TIMEOUT or OS_ERR_EVENT_QUEUE_TIMEOUT. There are two types of events in the SmartDSP OS: semaphores and queues. Event Semaphores A semaphore event is used to synchronize a task with an HWI, SWI, or another task. Semaphore events can be posted multiple times or accepted an equal number of times. To use a semaphore event for synchronization purposes, set its value to 0. For example, a task initiates an (I/O) operation and then waits for a semaphore. When the I/O operation finishes, an SWI, HWI, or another task sets the semaphore and the task resumes. The initialization of event semaphores is handled by the events base class. An application defines the number of event semaphores in the os_config.h file, using this definition: #define OS_TOTAL_NUM_OF_EVENT_SEMAPHORES 5 A software or hardware interrupt handler that waits for a semaphore, must call the non- blocking command osEventSemaphoreAccept(), or it will fail. Background tasks cannot pend on a semaphore because such tasks must never block. The running task can pend on a semaphore with a possible timeout time measured in ticks. The running context (task or interrupt) can always post to a semaphore. To create and delete a semaphore, use the functions shown in Listing 2.13: Listing 2.13 Functions for creating and deleting semaphore status = osEventSemaphoreFind(&s); OS_ASSERT_COND(status == OS_SUCCESS); status = osEventSemaphoreCreate(s, 0); OS_ASSERT_COND(status == OS_SUCCESS); status = osEventSemaphoreDelete(s); OS_ASSERT_COND(status == OS_SUCCESS); The following code snippet (Listing 2.14) shows an example of a task pointing to a semaphore, another task pending on it, and interrupt handler accepting it: SmartDSP OS User Guide 69
  • 70. Kernel Components Events Listing 2.14 Tasks pointing to and pending on a semaphore status = osEventSemaphorePend(S, TIMEOUT); //Task1 OS_ASSERT_COND(status == OS_SUCCESS); status = osEventSemaphorePost(S, &resumed_task); //Task 2 OS_ASSERT_COND(status == OS_SUCCESS); status = osEventSemaphoreAccept(s); //Interrupt Handler The functions available in the event semaphores module of the SmartDSP OS are listed in Table 2.8. Table 2.8 Functions Available for Event Semaphores Flow State Name Description Kernel bring up Already handled by the Events ‘base class’. Application bring up osEventSemaphoreFind Receives a handle to () create a semaphore event. osEventSemaphoreCrea Creates a semaphore te() event. Initializes a semaphore counter and an empty waiting list and places them in an event structure. Application runtime osEventSemaphorePend Pends on a counting () semaphore if semaphore counter is zero; otherwise, decrements and continues. osEventSemaphoreAcce Continues semaphore pt() without pending. Checks if semaphore counter is not zero, whereupon it decrements the counter. 70 SmartDSP OS User Guide
  • 71. Kernel Components Events Table 2.8 Functions Available for Event Semaphores (continued) Flow State Name Description osEventSemaphorePost Posts a counting () semaphore. If tasks are pending on the semaphore, it schedules them; otherwise, increments the counter and continues. osEventSemaphoreRese Removes all tasks t() pending on the event and schedule them if they are ready. Application tear down osEventSemaphoreDele Resets semaphore and te() deletes the semaphore. Releases the event structure used for the counting semaphore and resumes all tasks pending on it. Event Queues Event queues are used to store events, which are due to be processed. Event queues require both events and queues to be in the system. An application defines the number of event queues in the os_config.h file, as: #define OS_TOTAL_NUM_OF_EVENT_QUEUES 3 NOTE The function for deleting an event queue is not supported, yet. A handler that receives a message must call the non-blocking command, osEventQueueAccept(), or it will fail. Background tasks cannot pend on a queue, because such tasks must never block. To find and create an event queue, use the functions in Listing 2.15: Listing 2.15 Finding and creating an event queue status = osEventQueueFind(&Q); OS_ASSERT_COND(status == OS_SUCCESS); status = osEventQueueCreate(Q, SIZE); SmartDSP OS User Guide 71
  • 72. Kernel Components Events OS_ASSERT_COND(status == OS_SUCCESS); The following code snippet (Listing 2.16) illustrates an example of a task pointing to a queue, another task pending on it, and an interrupt handler accepting it: Listing 2.16 Tasks pointing to and pending on a queue status = osEventQueuePend(Q, &message, TIMEOUT); //Task 1 status = osEventQueuePost(Q, message, &resumed_task); // Task 2 OS_ASSERT_COND(status == OS_SUCCESS); status = osEventQueueAccept(Q, &message); //Interrupt Handler The functions available in the event queues module of the SmartDSP OS are listed in Table 2.9. Table 2.9 Functions Available for Event Queues Flow State Name Description Kernel bring up Already handled by the Events ‘base class’. Application bring up osEventQueueFind() Receives a handle to create a queue event. osEventQueueCreate( Creates a queue event. ) Initializes a queue and an empty waiting list. Then, it places a handle to this queue and to the empty waiting list in an event structure. 72 SmartDSP OS User Guide
  • 73. Kernel Components OS Tick Timers Table 2.9 Functions Available for Event Queues (continued) Flow State Name Description Application runtime osEventQueuePend() Pends on an event queue if queue is empty; otherwise, dequeues and continues. osEventQueueAccept( Continues without ) pending. It checks if there is a message available in the queue. If there is a message, it returns the message to the caller. osEventQueuePost() Posts a message to a queue. If tasks are pending on the queue, it posts messages on the tasks and schedules them; otherwise, enqueues. osEventQueueReset() Removes all tasks pending on the queue and schedules them if they are ready. Application tear down Not supported OS Tick Timers In the devices incorporating DSP subsystems with the SC3400 core and above, such as MSC814x and later, the tick functionality runs on timer zero on each individual DSP subsystem. The timer expiration triggers a hardware interrupt which activates a software interrupt. The OS provides #define constants for standard tick resolutions in smartdsp_os_device.h. Refer to SmartDSP OS API Reference Manual for details. Configuration of OS Tick Timers The tick functionality is defined in os_config.h as: #define OS_TICK ON #define OS_TICK_PRIORITY OS_SWI_PRIORITY0 SmartDSP OS User Guide 73
  • 74. Kernel Components Software Timers #define OS_TICK_PARAMETER MSC814X_TICK_DEFAULT The #define constant for tick period is calculated by the number of interrupts per second. Therefore, for 10[ms] period that would be (10^3)/10 or: #define MSC815X_TICK_010MS INTERRUPTS_PER_SEC_100 #define INTERRUPTS_PER_SEC_100 100 For example, if the intended tick period is 7[ms], the number of ticks per second and the OS_TICK_PARAMETER will be (10^3)/7 or 142.85. This number will be rounded down to 142 by the compiler since the kernel expects a uint32_t for the parameter. The DSP subsystem timer is configured by osTickIntProgram(): divider_value = g_core_clock*1000000/g_tick_parameter; Since the g_tick_parameter will be rounded off, the calculation comes to, 1000*1000000/ 142 which is equal to 0x6B74CD or 7042253. Having a 1Ghz (ergo the 1000) count to this number will give 7.042253[ms]. NOTE g_tick_parameter is the equivalent of OS_TICK_PARAMETER and will be rounded down by the compiler (defined as a uint32_t). NOTE This is the current implementation and prone to change. For tick frequency guarantee users must use the MSC81XX_TICK_XXXMS macros defined in smartdsp_os_device.h. Software Timers The software timers component of the SmartDSP OS kernel supports runtime association of software timer handlers, written in C or a C callable language. Software timers use the hardware tick timer as its point of reference. All software timer handlers run from the OS SWI assigned to the tick timer. The software interrupt handler checks the software timers, which are scheduled to expire on this tick, and calls their handler. Because software timers run as software interrupts, they are not as precise as hardware timers. Software timer handlers run in an interrupt (that is, system) context with the interrupt stack. You can enable and disable individual software timers, and set and change timer periods in the OS configuration file. At creation, a timer is specified as a one-shot timer or a periodic timer. A one-shot timer runs the associated timer function when the timer expires and does not run again. A periodic timer reloads its interval value each time the handler runs, and runs 74 SmartDSP OS User Guide
  • 75. Kernel Components Software Timers periodically. You can define the maximum number of software timers allowed by the system in the configuration file. Software timers have the granularity of the tick. A higher tick frequency allows better precision of software timers. A lower tick frequency causes less interrupt overhead on the core. Software timers require the tick functionality in the system that is defined in os_config.h, see Configuration of OS Tick Timers. Configuration of Software Timers The availability of software timers in the system is also configured in os_config.h as: #define OS_TOTAL_NUM_OF_SW_TIMERS 5 The functions available for the software timers module of the SmartDSP OS are listed in Table 2.10. Table 2.10 Functions Available for Software Timers Flow State Name Description Kernel bring up (the user osTimerInitialize() Initializes the software application does not call timers module. these functions specifically. Instead, osInitialize() calls these functions based on the parameters from os_config.h and configurations from msc81xx_config.c) Application bring up osTimerFind() Finds the first available software timer number. osTimerCreate() Creates a software timer and sets its parameters, such as timer number, timer mode, timer interval, and handler. Application runtime osTimerStart() or Starts the given osTimerStartDelayed() software timer. SmartDSP OS User Guide 75
  • 76. Kernel Components Software Timers Table 2.10 Functions Available for Software Timers (continued) Flow State Name Description osTimerStop() Stops the given software timer. osTimerSetInterval() Sets the interval of the given software timer. osTimerSelf() Retrieves the number of the currently active software timer. Application tear down osTimerDelete() Deletes the given software timer from the system. The source code in Listing 2.17 dynamically creates a timer using osTimerFind(). The new timer expires only once (OS_TIMER_ONE_SHOT). The timer expires after five system ticks. When the timer is created, it does not start automatically. The next part of the listing starts the timer using osTimerStart(). Listing 2.17 Dynamically creating a one-shot timer os_timer_handle timer1; status = osTimerCreate(timer1, // timer object OS_TIMER_ONE_SHOT, // timer mode 5, // ticks timeout timerTest1); // timer handler if (status != OS_SUCCESS) OS_ASSERT; // Start the timer status = osTimerStart(timer1); if (status != OS_SUCCESS) OS_ASSERT; void timerTest1() { // Do something... } Listing 2.18 uses the previous timer, changes the tick timeout from 5 to 10, and restarts the timer for a single expiration. Listing 2.18 Changing the timeout period of the timer // Set the timer's timeout 76 SmartDSP OS User Guide
  • 77. Kernel Components Software Timers status = osTimerSetInterval(timer1, 10); if (status != OS_SUCCESS) OS_ASSERT; // Start the timer status = osTimerStart(timer1); if (status != OS_SUCCESS) OS_ASSERT; Listing 2.19 dynamically creates a timer using osTimerFind(). The new timer expires repetitively because it is a periodic timer. The timer expires every time 20 system ticks elapse. When the timer is created, it does not start automatically. The next part of the listing starts the timer. To stop a timer, use the osTimerStop() function. Listing 2.19 Dynamically creating a periodic timer os_timer_handle timer2; status = osTimerCreate(timer2, // timer object OS_TIMER_PERIODIC, // timer mode 20, // ticks timeout timerTest2); // timer handler if (status != OS_SUCCESS) OS_ASSERT; // Start the timer status = osTimerStart(timer2); if (status != OS_SUCCESS) OS_ASSERT; void timerTest2(void) { // Do something else... } // Stop the timer status = osTimerStop(timer2); if (status != OS_SUCCESS) OS_ASSERT; Listing 2.20 dynamically creates a timer using osTimerFind(). The new timer expires once because it is a one-shot timer. The timer expires after 20 system ticks elapse. When the timer is created it does not start automatically. The timer handler deletes the timer. Listing 2.20 Dynamically creating a one-shot timer that deletes itself after it expires os_timer_handle timer3 osTimerFind(&timer3); status = osTimerCreate(timer3, // timer object SmartDSP OS User Guide 77
  • 78. Kernel Components Hardware Timers OS_TIMER_ONE_SHOT, // timer mode 20, // ticks timeout timerTest3); // timer handler if (status != OS_SUCCESS) OS_ASSERT; // Start the timer status = osTimerStart(timer3); if (status != OS_SUCCESS) OS_ASSERT; void timerTest3() { os_timer_handle self; // Delete the timer status = osTimerSelf(&self); if (status != OS_SUCCESS) OS_ASSERT; status = osTimerDelete(self); if (status != OS_SUCCESS) OS_ASSERT; } Hardware Timers The hardware timers are a group of timers running at system (not core) frequency. The hardware timers are shared among all cores and their sharing is handled by the SmartDSP OS drivers. Hardware timers are part of the SoC. The SoC hardware timer module contains four quadrates of four timers each. In devices with four cores, each core owns a quadrate. In devices with six cores, each core owns half a quadrate. This means that there are four hardware timers not enabled by the OS The hardware timers in the 8144/8156 processors are 16-bit timers which can be clocked from multiple optional input clocks. In 8144/8156 processors, there are four quadrates of clocks that make a total of sixteen 16-bit clocks. The SmartDSP OS supplies hardware timer implementation for the different architectures, wrapped with a common, minimal API. Hardware timers exist on most underlying hardware and work in a similar way. The SmartDSP OS API for hardware timers is similar to the software timers API, except that you must specify the clock source for the timer when they are created. Hardware timers have a finer granularity than the OS clock because they do not need to be tied to the OS clock. Hardware timers have the granularity of the driving clock, based on SoC support. 78 SmartDSP OS User Guide
  • 79. Kernel Components Hardware Timers Configuration of Hardware Timers The availability of hardware timers in the system is configured in os_config.h, as: #define OS_HW_TIMERS ON The functions available for the hardware timers module of the SmartDSP OS are listed in Table 2.11. Table 2.11 Functions Available for Hardware Timers Flow State Name Description Kernel bring up (the user osHWTimerInitializ Initializes the hardware application does not call e() timers module. these functions specifically. Instead, osInitialize() calls these functions based on the parameters from os_config.h and configurations from msc81xx_config.c) Application bring up osHWTimerFind() Finds the first available hardware timer number. osHWTimerCreate() Creates a hardware timer and sets its parameters, such as timer number, timer mode, clock source, timer interval, handler, and priority. Application runtime osHWTimerStart() Starts the given hardware timer. osHWTimerStop() Stops the given hardware timer. osHWTimerSetInterv Creates a hardware timer al() and sets its parameters. osHWTimerClearEven Clears the event bit of the t() given hardware timer. Hardware timers can be set as OS_TIMER_ONE_SHOT, OS_TIMER_PERIODIC or OS_TIMER_FREE_RUN. When the timer expires, an application defined handler (set in osHwTimerCreate) is called. SmartDSP OS User Guide 79
  • 80. Kernel Components Hardware Timers NOTE OS does not call osHwTimerClearEvent function. The application defined handler must call this function in order to clear the interrupt. 80 SmartDSP OS User Guide
  • 81. 3 Hardware Abstraction Layers (HAL) This chapter explains Hardware Abstraction Layers (HAL). A HAL allows an application to stream Input/Output (I/O) data to a hardware device using device's Low Level Driver (LLD). NOTE In SmartDSP OS, a HAL is also referred to as an Abstraction Module. This chapter consists of the following topics: • HAL in SmartDSP OS • Buffered I/O (BIO) Module • Coprocessor (COP) Module • Synchronized I/O (SIO) Module • Character I/O (CIO) Module HAL in SmartDSP OS This topic explains the conceptual model and workflow of HAL in the SmartDSP OS. This topic consists of the following sub-topics: • Conceptual Model • Conceptual Workflow Conceptual Model HAL in the SmartDSP OS consists of two layers: • Serializer The serializer interacts with the user application to stream I/O data to a hardware device. The SmartDSP OS implements different serializer modules for different types of I/O data and different hardware devices. Each serializer module provides a high-level API to the user application for interacting with the corresponding LLD/ hardware device. SmartDSP OS User Guide 81
  • 82. Hardware Abstraction Layers (HAL) HAL in SmartDSP OS Table 3.1 lists the supported serializer modules and their functionality in the SmartDSP OS. • LLD The LLD interacts with the actual hardware device to perform I/O operations. The LLD uses LLD API to communicate with serializer. Table 3.1 Serializer Modules in SmartDSP OS Serializer Module Name Functionality Buffered I/O (BIO) Module Supports the hardware devices, such as Ethernet, that transmit and receive data using data packets Coprocessor (COP) Module Supports co-processors, such as MAPLE Synchronized I/O (SIO) Module Supports the hardware devices, where both the transmit and the receive processes are timed by the hardware, such as TDM Character I/O (CIO) Module Supports character and stream oriented devices, such as UART Figure 3.1 shows the conceptual model of HAL in the SmartDSP OS. Figure 3.1 Conceptual Model of HAL in SmartDSP OS 82 SmartDSP OS User Guide
  • 83. Hardware Abstraction Layers (HAL) Buffered I/O (BIO) Module The user application calls the hardware-independent high-level API functions, and the LLD implements the device specific functionality. Conceptual Workflow Figure 3.2 shows the conceptual workflow of an application using HAL in the SmartDSP OS to send and receive data to a hardware device. Figure 3.2 Conceptual Workflow of HAL in SmartDSP OS NOTE A channel is an abstract data path between the LLD and the hardware device. All I/O operations use channels to send and receive data to a hardware device. For duplex communication, two channels (transmit and receive) are required. Buffered I/O (BIO) Module The BIO module provides high-level API and LLD for streaming I/O data to hardware devices, such as Ethernet, that transmit and receive data using data packets. The BIO module also performs serialization of transmitted and received data packets. This topic consists of the following sub-topics: • BIO Layers • BIO Initialization Workflow SmartDSP OS User Guide 83
  • 84. Hardware Abstraction Layers (HAL) Buffered I/O (BIO) Module • BIO Runtime Workflow BIO Layers The BIO module consists of two layers: • BIO Serializer BIO Serializer is the upper layer. It interacts with the user application using high- level API, and performs serialization of the I/O data packets. Also, the upper layer defines callback functions that the BIO module uses to pass the control back to the user application. • BIO LLD BIO LLD is the lower layer. It interacts with the actual BIO hardware device to perform I/O operations. The BIO LLD for each BIO device must support the BIO LLD API in the SmartDSP OS. For more information on the BIO LLD API, refer to SmartDSP OS API Reference Manual. The BIO module uses a frame data structure to transfer the data between: • user application • BIO serializer • BIO LLD The SmartDSP OS API provides a SmartDSP OS frame data structure that you can use. You can also manage the frames using user-defined data structures. The user application should use the same data structure as used in the LLD frame data structure. BIO Initialization Workflow This topic explains the workflow of the BIO module during system (SmartDSP OS kernel) and user application initialization. This topic consists of the following sub-topics: • BIO Initialization Workflow - System (Kernel) • BIO Initialization Workflow - User Application BIO Initialization Workflow - System (Kernel) During system initialization: 84 SmartDSP OS User Guide
  • 85. Hardware Abstraction Layers (HAL) Buffered I/O (BIO) Module 1. the SmartDSP OS kernel initializes the LLD of all the BIO devices NOTE Each LLD is initialized only once, even in a multi-core environment. 2. the LLD initialization function initializes the corresponding hardware device 3. the LLD initialization function registers the LLD with the BIO serializer The registration information contains function pointers that the BIO serializer uses to translate the high-level API functions to the corresponding LLD functions during application runtime. 4. the number of BIO devices that the system supports is set using following definition in the os_config.h file: #define OS_TOTAL_NUM_OF_BIO_DEVICES (MSC815X_UEC0 + MSC815X_UEC1 + MSC815X_RIONET0 + MSC815X_RIONET1) 5. the maximum number of channels, supported per BIO device, is set BIO Initialization Workflow - User Application During application initialization: 1. BIO device is opened The user application calls the high-level API function, osBioDeviceOpen, to open a BIO device 2. Tx/Rx channel in the BIO device is opened The user application calls the high-level API function, osBioChannelOpen, to open a Tx/Rx channel in the BIO device 3. the memory required for the BIO channels is allocated You can allocate the memory by creating a static array of the bio_channel_t structure and specify the array size as the number of required channels. NOTE The bio_channel_t structure defines the structure of a BIO channel. For more information, refer to SmartDSP OS API Reference Manual. 4. the number of queues are set The BIO serializer uses queues to hold transmitted and received frames. • For each BIO Tx channel, the BIO serializer uses Tx Confirmation Queue to hold the frames that are transmitted to the LLD. If the BIO serializer fails in transmitting a frame to the LLD, the BIO serializer notifies the user application, and does not put corresponding frame into the confirmation queue. SmartDSP OS User Guide 85
  • 86. Hardware Abstraction Layers (HAL) Buffered I/O (BIO) Module • For each BIO Rx channel, the BIO serializer uses: – one queue to hold the received frames – another queue to hold the empty data buffers The LLD must request empty data buffers from the BIO serializer before trying to receive new data from the BIO device. The LLD can also choose a common buffers pool for all the Rx channels. NOTE The buffers pool consists of multiple chunks of memory, which the SmartDSP OS memory manager maintains. The memory chunks are not stored in any order. When the LLD chooses a common buffers pool for the all the Rx channels, the LLD gets empty buffers before having to identify the Rx channel. Once the data is received into empty buffers, the LLD can choose one of these options: – let the BIO serializer build the received frames from the buffers (recommended) The serializer builds a new frame structure according to the buffer length (removing buffers from the buffers queue as needed), and puts the built frame into the received frames queue. – build the frames by itself; used for receiving extended frame structures that contain additional information (other than the data buffers) The LLD passes the pointer of the built frame to the BIO serializer. The serializer only inserts the frame into the received frames queue. In case of errors in the received data (for example, CRC errors), the frame is discarded. The serializer does not build a new frame, but can notify the error using application's receive callback function. To determine the number of queues that the BIO serializer requires, use the method that Table 3.2 explains. Table 3.2 Determining the Number of Required Queues Operating Mode Number of Queues Required BIO serializer builds the frame, and no BIO_dev_queues = num_of_tx_channels common buffers pool is used + (2*num_of_rx_channels) 86 SmartDSP OS User Guide
  • 87. Hardware Abstraction Layers (HAL) Buffered I/O (BIO) Module Table 3.2 Determining the Number of Required Queues (continued) Operating Mode Number of Queues Required BIO serializer builds the frame, and BIO_dev_queues = num_of_tx_channels common buffers pool is used +1+ num_of_rx_channels_that_use_the_com mon_pool + (2*num_of_rx_channels_that_use_anoth er_pool) LLD builds the frame, and any type of BIO_dev_queues = num_of_tx_channels buffer pool is used + num_of_rx_channels BIO Runtime Workflow This topic explains the workflow of the BIO module during application runtime. This topic consists of the following sub-topics: • BIO Runtime Workflow - Transmit • BIO Runtime Workflow - Receive BIO Runtime Workflow - Transmit The BIO Tx channel must be open in the write mode, before the user application can transmit any data to a BIO device. The transmit process consists of the following steps: 1. The user application uses the high-level API function, osBioChannelTx, and specifies a pointer to the Tx channel and a pointer to the frame that is to be transmitted. 2. The serializer calls the LLD transmit function, and specifies the frame that is to be transmitted. In addition, the serializer queues the frame in Tx confirmation queue. 3. The LLD transmits the frame to the BIO device. 4. The LLD calls the LLD API function, bioChannelTxCb, and notifies the serializer about the number of transmitted frames. 5. The serializer de-queues the specified frames from Tx confirmation queue. 6. The serializer calls the transmit callback function of the user application, if any defined, for each transmitted frame. If the user application does not specify any transmit callback function, the serializer releases all the transmitted frames back to the frames pool. SmartDSP OS User Guide 87
  • 88. Hardware Abstraction Layers (HAL) Coprocessor (COP) Module BIO Runtime Workflow - Receive The BIO Rx channel must be open in the read mode, before the user application can receive any data from a BIO device. The receive process consists of the following steps: 1. The LLD requests an empty buffer from the BIO serializer for a specific Rx channel using the LLD API function, bioChannelRxBufferGet. The LLD can also request an empty buffer from a common buffers pool. 2. The serializer allocates a new buffer to the LLD. 3. The LLD replaces the old buffer with the new buffer, if the buffers use Buffer Descriptors (BD). 4. The empty buffer receives the data. 5. The LLD notifies the serializer using the LLD API function bioChannelRxCb, and specifies a pointer to the Rx channel and length of the received frame. The LLD may also build the frame by itself, and use the LLD API function, bioChannelRxFrameCb to notify the serializer. 6. The serializer puts the received frame into the received frames queue. 7. The serializer calls the receive callback function of the user application, if any defined, for each frame that is put into the received frames queue. 8. The user application de-queues the frames from the received frames queue. Coprocessor (COP) Module The COP module provides high-level API and LLD for dispatching jobs to a COP hardware device for execution. The SmartDSP OS currently supports SEC and MAPLE COP devices. NOTE The COP module was introduced in MSC814x, and is not available for earlier devices. The COP module also performs serialization of jobs. This topic consists of the following sub-topics: • COP Layers • COP Initialization Workflow • COP Runtime Workflow 88 SmartDSP OS User Guide
  • 89. Hardware Abstraction Layers (HAL) Coprocessor (COP) Module COP Layers The COP module consists of two layers: • COP Serializer COP Serializer is the upper layer. It interacts with the user application using high- level API, and also performs serialization of jobs before dispatching to the COP device. In addition, the COP serializer ensures that job results are returned from the COP LLD to the user application in the order of dispatch. • COP LLD COP LLD is the lower layer. It interacts with the actual COP device to dispatch jobs. The COP LLD for each COP device must support the COP LLD API in the SmartDSP OS. For more information on COP LLD API, refer to SmartDSP OS API Reference Manual. NOTE Generally, jobs dispatched to a COP device begin and terminate within the device itself. COP Initialization Workflow This topic explains the workflow of the COP module during system (SmartDSP OS kernel) and while user application initialization. This topic consists of the following sub-topics: • COP Initialization Workflow - System (Kernel) • COP Initialization Workflow - User Application COP Initialization Workflow - System (Kernel) During system initialization: 1. the COP device is registered with the COP serializer using the LLD API function, copRegister The registration information contains function pointers that the COP serializer uses to translate the high-level API functions to the corresponding LLD functions during application runtime. 2. the number of COP devices that the system supports is set using following definition in the os_config.h file: #define OS_TOTAL_NUM_OF_COP_DEVICES (MSC815X_SEC + MAPLE + MAPLE_TVPE + MAPLE_FFTPE + MAPLE_DFTPE + MAPLE_CRCPE) SmartDSP OS User Guide 89
  • 90. Hardware Abstraction Layers (HAL) Coprocessor (COP) Module 3. the maximum number of channels, supported per COP device, is set COP Initialization Workflow - User Application During application initialization: 1. COP device is opened The user application calls the high-level API function, osCopDeviceOpen, to open a COP device. 2. COP channel in the COP device is opened The user application calls the high-level API function, osCopChannelOpen, to open a COP channel in the COP device. 3. the memory required for the COP channels is allocated You can allocate the memory by creating a static array of the cop_channel_t structure and specify the array size as the number of required channels. NOTE The cop_channel_t structure defines the structure of a COP channel. For more information, refer to SmartDSP OS API Reference Manual. 4. the total number of queues, one for each channel, is set in the os_config.h file using the OS_TOTAL_NUM_OF_QUEUES definition COP Runtime Workflow This topic explains the workflow of the COP module during application runtime. This topic consists of the following sub-topics: • COP Runtime Workflow - Job Dispatch NOTE There is no receive path in the COP module. COP Runtime Workflow - Job Dispatch The COP Tx channel must be open in the write mode, before the user application can dispatch any jobs to a COP device. The transmit process consists of the following steps: 1. The user application uses the high-level API function, osCopChannelDispatch, and specifies a pointer to a valid COP channel and a pointer to an array of job handles. 2. The dispatch request is assigned to the COP LLD. 90 SmartDSP OS User Guide
  • 91. Hardware Abstraction Layers (HAL) Synchronized I/O (SIO) Module 3. The LLD calls the LLD API function, copChannelDispatchCb, and notifies the serializer that dispatched job has finished executing. 4. The serializer calls the callback function of the user application, if any defined. Synchronized I/O (SIO) Module The SIO module provides high-level API and the LLD for streaming I/O data to hardware devices, such as TDM, where both the transmit and the receive processes are timed by the hardware. The SIO module also performs serialization of transmitted and received data buffers. This topic consists of the following sub-topics: • SIO Layers • SIO Initialization Workflow • SIO Runtime Workflow SIO Layers The SIO module consists of two layers: • SIO Serializer SIO Serializer is the upper layer. It interacts with the user application using high- level API, and performs serialization of the data buffers. • SIO LLD SIO LLD is the lower layer. It interacts with the actual SIO hardware device to perform I/O operations. The SIO LLD for each SIO hardware device must support the SIO LLD API in the SmartDSP OS. For more information on SIO LLD API, refer to SmartDSP OS API Reference Manual. Using SIO is recommended when the hardware device uses a cyclic buffer, which may be divided into smaller sub-buffers, to transmit and receive data during specific time slots. This approach imposes hard real-time constraints on the user application, for example: • an under-run error, if the user application does not free the buffer, and if it is seized • unused time slot, if the user application does not provide any data for transmission during the specified time slot SIO Initialization Workflow This topic explains the workflow of the SIO module during system (SmartDSP OS kernel) and while user application initialization. SmartDSP OS User Guide 91
  • 92. Hardware Abstraction Layers (HAL) Synchronized I/O (SIO) Module This topic consists of the following sub-topics: • SIO Initialization Workflow - System (Kernel) • SIO Initialization Workflow - User Application SIO Initialization Workflow - System (Kernel) During system initialization: 1. the SmartDSP OS kernel initializes the LLD of all the SIO devices NOTE Each LLD is initialized only once, even in a multi-core environment. 2. the LLD initialization function initializes the corresponding hardware device 3. the LLD initialization function registers the LLD with the SIO serializer The registration information contains function pointers that the SIO serializer uses to translate the high-level API functions to the corresponding LLD functions during application runtime. 4. the number of SIO devices that the system supports is set using following definition in the os_config.h file: #define OS_TOTAL_NUM_OF_SIO_DEVICES (MSC815X_TDM0 + MSC815X_TDM1 + MSC815X_TDM2 + MSC815X_TDM4) 5. the maximum number of channels, supported per SIO device, is set SIO Initialization Workflow - User Application During application initialization: 1. SIO device is opened The user application calls the high-level API function, osSioDeviceOpen, to open a SIO device. 2. Tx/Rx channel in the SIO device is opened The user application calls the high-level API function, osSioChannelOpen, to open a Tx/Rx channel in the SIO device. When the SIO serializer opens a channel, the serializer submits an array of buffers to the LLD memory, and a reference to an index in the array of buffers. The LLD maintains an index of the current buffer and returns its reference to the user application. The serializer maintains an index of the buffer currently held by the user application. By comparing the LLD's index with the user application's index, the 92 SmartDSP OS User Guide
  • 93. Hardware Abstraction Layers (HAL) Character I/O (CIO) Module serializer knows if an under-run occurred and if there is a new buffer that is ready to be passed to the user application. 3. the memory required for the SIO channels is allocated You can allocate the memory by creating a static array of the sio_channel_t structure and specify the array size as the number of required channels. NOTE The sio_channel_t structure defines the structure of a SIO channel. For more information, refer to SmartDSP OS API Reference Manual. SIO Runtime Workflow This topic explains the workflow of the SIO module during application runtime. A SIO channel must be open in the write or read mode, before the user application can transmit or read any data to a SIO device. The transmit/read process consists of the following steps: 1. The user application uses the high-level API function, osSioBufferGet, and receives a buffer and a buffer length from the Tx (write) or Rx (read) channel. The requested buffer is available to the user application as long as the buffer is not requested by the LLD. If the LLD requests the buffer while the user application is still using it, the serializer calls the application under-run callback and the buffer is seized from the user application. 2. The user application: • fills the buffer with the data if the buffer belongs to a Tx channel, and notifies the serializer to increment its index • reads the buffer if it belongs to a Rx channel, and the LLD increments its index 3. The user application uses the high-level API function, osSioBufferPut, and returns the buffer to the LLD Character I/O (CIO) Module The CIO module provides high-level API and LLD for streaming I/O data to hardware devices, such as UART, that transmit and receive data as a stream of characters/bytes. The CIO module also performs serialization of transmitted and received stream of characters. This topic consists of the following sub-topics: • CIO Layers • CIO Initialization Workflow SmartDSP OS User Guide 93
  • 94. Hardware Abstraction Layers (HAL) Character I/O (CIO) Module • CIO Runtime Workflow CIO Layers The CIO module consists of two layers: • CIO Serializer CIO Serializer is the upper layer. It interacts with the user application using high- level API, and performs serialization of the I/O stream of characters. • CIO LLD CIO LLD is the lower layer. It interacts with the actual CIO hardware device to perform I/O operations. The CIO LLD for each CIO device must support the CIO LLD API in the SmartDSP OS. For more information on CIO LLD API, refer to SmartDSP OS API Reference Manual. CIO Initialization Workflow This topic explains the workflow of the CIO module during system (SmartDSP OS kernel) and user application initialization. This topic consists of the following sub-topics: • CIO Initialization Workflow - System (Kernel) • CIO Initialization Workflow - User Application CIO Initialization Workflow - System (Kernel) During system initialization: 1. the SmartDSP OS kernel initializes the LLD of all the CIO devices. NOTE Each LLD is initialized only once, even in a multi-core environment. 2. the LLD initialization function initializes the corresponding hardware device. 3. the LLD initialization function registers the LLD with the CIO serializer. The registration information contains function pointers that the CIO serializer uses to translate the high-level API functions to the corresponding LLD functions during application runtime. 94 SmartDSP OS User Guide
  • 95. Hardware Abstraction Layers (HAL) Character I/O (CIO) Module 4. the number of CIO devices that the system supports is set using following definition in the os_config.h file: #define OS_TOTAL_NUM_OF_CIO_DEVICES (MSC815X_DOORBELL + MSC815X_UART + MSC815X_I2C + MSC815X_SPI) 5. the maximum number of channels, supported per CIO device, is set. CIO Initialization Workflow - User Application During application initialization: 1. CIO device is opened The user application calls the high-level API function, osCioDeviceOpen, to open a CIO device. 2. Tx/Rx channel in the CIO device is opened The user application calls the high-level API function, osCioChannelOpen, to open a Tx/Rx channel in the CIO device. When the CIO serializer opens a channel, the user application sends a character array to the serializer. The serializer assigns this character array to both Tx and Rx CIO channels. 3. the memory required for the CIO channels is allocated You can allocate the memory by creating a static array of the cio_channel_t structure and specify the array size as the number of required channels. NOTE The cio_channel_t structure defines the structure of a CIO channel. For more information, refer to SmartDSP OS API Reference Manual. CIO Runtime Workflow This topic explains the workflow of the CIO module during application runtime. The CIO serializer uses two dynamic pointers to transmit/receive the stream of characters: • one pointer points to the current transmitted/received data • another pointer points to the next free location at which the new data will be transmitted/received This topic consists of the following sub-topics: • CIO Runtime Workflow - Transmit • CIO Runtime Workflow - Receive SmartDSP OS User Guide 95
  • 96. Hardware Abstraction Layers (HAL) Character I/O (CIO) Module CIO Runtime Workflow - Transmit The CIO Tx channel must be open in the write mode, before the user application can send a stream of characters to a CIO device. The transmit process consists of the following steps: 1. The user application uses the high-level API function, osCioChannelBufferGet, and receives a pointer to a free buffer. 2. The user application fills the buffer with the data, and uses the high-level API function, osCioChannelTxBufferPut, to notify the serializer that the data is ready for transmission. 3. The serializer calls the LLD transmit function. 4. The LLD transmits the data to the CIO device. 5. The LLD calls the LLD API function, cioChannelTxCb, and notifies the serializer about the number of transmitted bytes. 6. The serializer calls the transmit callback function of the user application, if any defined, for each transmitted buffer of data. NOTE Every osCioChannelBufferGet call must have a corresponding osCioChannelTxBufferPut call, or else the serialization process may lead to corrupt data. CIO Runtime Workflow - Receive The CIO Rx channel must be open in the read mode, before the user application can read a stream of characters from a CIO device. The receive process consists of the following steps: 1. The LLD uses the high-level API function, osCioChannelBufferGet, and receives a pointer to a free buffer. 2. The CIO device sends an interrupt to the LLD, and the LLD fills the buffer with the received data. 3. The LLD calls the LLD API function, cioChannelRxCb, and notifies the serializer that the data is received. 4. The serializer calls the receive callback function of the user application, if any defined, for each received buffer of data. 5. The user application uses the high-level API function, osCioChannelRxBufferGet, and receives a pointer to the received data. 96 SmartDSP OS User Guide
  • 97. Hardware Abstraction Layers (HAL) Character I/O (CIO) Module 6. The user application uses the high-level API function, osCioChannelRxBufferFree, and notifies the serializer that the data processing is finished. NOTE Every osCioChannelRxBufferGet call must have a corresponding osCioChannelRxBufferFree call, or else the serialization process may lead to corrupt data. SmartDSP OS User Guide 97
  • 98. Hardware Abstraction Layers (HAL) Character I/O (CIO) Module 98 SmartDSP OS User Guide
  • 99. 4 Drivers A driver program allows SW, which utilizes the OS, to interact with a peripheral device. The SmartDSP OS, • supports a unified, cross-device API for generic HW drivers; • provides a device-specific API for device-specific HW; and, • supports MSC814x, MSC815x, and MSC825x processor driver families. The five SmartDSP OS driver types are noted in the below table. Table 4.1 SmartDSP Drivers Driver Description Example DMA Provides a unified API. • DMA controllers BIO Provides a unified API for all • ETH messages frame type drivers. • RapidIO® messages COP Provides a unified API for all • SEC and MAPLE- co-processors. B SIO Provides a unified API for • TDM devices with HW-timed Rx/ Tx processes. CIO Provides a unified API for • UART and I²C non frame-based devices (that lack a logical division of the data into frames or packets). This chapter has sections detailing the following SmartDSP OS drivers: • Direct Memory Access (System DMA)demosstarcoremsc815xuart • OCeaN DMA • QUICC Engine Unified Ethernet Controller (QE UEC) • Serial RapidIO (sRIO) • Doorbell SmartDSP OS User Guide 99
  • 100. Drivers Direct Memory Access (System DMA) • PCI Express (PCIe) • Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) • RIONET • Time Division Multiplexing (TDM) • Universal Asynchronous Receiver/Transmitter (UART) Direct Memory Access (System DMA) A System DMA is a HW controller; it off loads, from the core, the task of moving data from one location to another. SmartDSP OS provides a unified, cross-platform API for the System DMA driver and, where necessary, a platform-specific API. Features SmartDSP OS System DMA LLD features are noted below. • Full exposure of all HW features. • Functions inlined for performance gain. • Generic and SoC-specific APIs. • Ability to pre-program BD rings (chains). • Ability to modify existing BDs (transfer/buffer). • Interrupt/polling at job completion. • Assignment of channels-to-cores at compilation time. Architecture This section covers the SW architecture of the System DMA driver. Driver Components This section details System DMA driver components found in the SmartDSP OS. See Table 4.2 and Figure 4.1 for further details. 100 SmartDSP OS User Guide
  • 101. Drivers Direct Memory Access (System DMA) Table 4.2 System DMA Components Components Description Controller • Represents the actual HW block. • HW block acts as follows: – generates access to the system bus; – manages data transfers between memory and HW devices; and – manages multiple channels. • Each channel can be programmed to move data from one place to another, independent of other channels. Channel • Represents the actual HW channel for data transfers. • Executes chains of DMA transfers. • Handles interrupts generated by DMA transfers. • Pre-allocated to a given core at compilation time. Chain • Represents a BD ring. • BD ring assembles DMA transfers in a BD chain. • Can be inactive. • Executable by any channel. Transfer/Buffer • Represents a BD; each BD describes DMA transaction attributes. Transfer • Symmetric 1D (classic) DMA transaction. • Includes all related R/W transaction attributes. Buffer • Representation of a specific HW DMA BD implementation. • Describes R/W transaction attributes of 1D or more. • Can include other HW-specific features. • See SmartDSP OS API Reference Manual. SmartDSP OS User Guide 101
  • 102. Drivers Direct Memory Access (System DMA) Figure 4.1 System DMA Module Structure Design Decisions Design decisions, along with their reasoning, are noted below. 1. The System DMA driver does not support cycle consuming cache and virtual addressing operations in the LLD. • Driver was written to minimize runtime overhead. • Driver API enables runtime modifications of pre-programmed BDs. 2. Many System DMA driver functions are statically inlined. • Minimizes the number of function calls as well as driver overhead. 3. Assigning channels-to-cores occurs at compilation time. • Minimizes the driver’s program memory footprint. Data Flow This section outlines the runtime data flow. 1. Application pre-configures one (or more) BD chains. 2. Application attaches one of the chains to a channel and activates the channel. 3. Channel chronologically iterates the BDs—in the order they were attached to the chain—and executes them. 4. Every application-modifiable BD attribute is defined; they cannot be changed during execution. 102 SmartDSP OS User Guide
  • 103. Drivers Direct Memory Access (System DMA) 5. Channel completes execution. 6. Application reactivates a given chain, swaps it for another, or becomes idle. In System DMA implementations, as configured by the application, the channel can be frozen during chain execution. Later, the application can unfreeze the channel. See API. Programming Model This section covers driver bring-up—first by the OS, then by the application-chosen API. General The System DMA consists of two API families. • Generic DMA concept—API is prefixed with osDma. • Device-specific family—API is prefixed by the device name; e g., msc815xDma. See the SmartDSP OS API Reference Manual for a complete list of DMA LLD API. Table 4.3 describes both architecture-independent and dependent APIs. Table 4.3 Architecture-Independent/Dependant APIs Architecture API Functions Description Architecture-independent Functions include: • Uses API functions • osDmaChannelO regardless of (see Table 4.4) pen() the HW • osDmaChainCre architecture; ate() e.g., Works. • osDmaChannelB ind() Architecture-dependant API Functions include: • Uses functions • msc814xDmaCha when the HW nnelDefrost() cannot be • msc815xDmaCha used for all architectures; nnelDisable() e.g., Common. • Header file: includear chstarcor emsc81xx msc81xx_dm a.h SmartDSP OS User Guide 103
  • 104. Drivers Direct Memory Access (System DMA) Calling Sequence Example Table 4.4 describes functions included in the architecture-independent API of the SmartDSP OS DMA driver. The functions include kernel bring-up, application bring-up, application runtime, and application teardown. Table 4.4 Architecture-Independent API State Function Description Kernel Bring-up osInitialize()-> • User application does osArchDevicesInitialize() not directly call these -> functions. osDmaInitialize() • osInitialize() calls osDmaInitialize( )— as based on os_config.h defines and msc81xx_config.c configuration structures. • Initializes System DMA driver. 104 SmartDSP OS User Guide
  • 105. Drivers Direct Memory Access (System DMA) Table 4.4 Architecture-Independent API State Function Description Application Bring- osDmaControllerOpen() • Must be first function up called. • Returns a DMA controller handle. • Handle is a parameter in calling other functions. osDmaChannelOpen() • Opens a pre-allocated channel. • Initializes channel structure as per configuration parameters. osDmaChainCreate() • Creates a DMA chain. • Initializes chain structure as per configuration parameters. osDmaChainTransferAdd() • Adds a transfer to a DMA chain. osDmaChainTransferAddEx() • Adds a transfer to a DMA chain. • Returns a handle to the transfer. • Handle can be used to modify transfer attributes. Application osDmaChannelBind() • Binds a chain to a Runtime channel. osDmaChannelStart() • Starts execution of a bound chain(s) on a DMA channel. osDmaChannelIsActive() • Polls the DMA channel to check its state (active/idle). SmartDSP OS User Guide 105
  • 106. Drivers Direct Memory Access (System DMA) Table 4.4 Architecture-Independent API State Function Description Application osDmaChainDelete() • Releases DMA chain Teardown resources (except memory). • Removes a chain from the DMA controller. osDmaChannelClose() • Releases DMA channel resources (except memory). To populate a chain, the application can use the architecture-independent transfer concept, architecture-dependent buffer concept, or a combination of both. The buffer allows users to program each side (R/W) of the chain as an individual entity; this allows for a mix of HW-enabled features such as BD dimension, freeze dimension, etc. The application is responsible for balancing the number of DMA channel R/W bytes. Table 4.5 Architecture-Dependent API State Function Description Bring-up msc815xDmaChainBufferAdd() • Appends a buffer to a DMA chain. msc815xDmaChainBufferAddEx( • Appends a buffer and ) returns a handle to a DMA chain. Runtime msc815xDmaChannelFreeze() • Freezes a DMA channel. msc815xDmaChannelDefrost() • Unfreezes a DMA channel. msc815xDmaChannelDisable() • Disables a DMA channel. NOTE Common MSC814x and MSC815x architecture-specific features: - share a similar API - prefixed by the device name. 106 SmartDSP OS User Guide
  • 107. Drivers Direct Memory Access (System DMA) Functionality Initialization Follow these steps to initialize the DMA: 1. Enable DMA support by setting #define MSC81XX_DMA ON in the application os_config.h file. 2. Allocate memory; this enables the driver to handle a DMA channel. • User application determines memory size: /* Allocate memory for channel use. */ uint8_t dma_channel[DMA_SIZE_OF_MEMORY_FOR_CHANNEL_USE]; 3. Allocate memory for a DMA chain handle. Allocation reflects both the DMA chain type and the maximum number of associated DMA transfers. • User application determines DMA chain, memory size: DMA_SIZE_OF_MEMORY_FOR_CHAIN_USE(<NUM_BUFFERS>) • Above code example allocates memory for a default chain type: /* Allocate memory for chain with two transfers. */ uint8_t dma_chain_memory[DMA_SIZE_OF_MEMORY_FOR_CHAIN_USE(2)]; 4. Get DMA controller handle using osDmaControllerOpen(). • Function returns the handle to the driver-allocated DMA controller. • User application must retrieve this handle to open DMA channels and create DMA chains. 5. Open controller DMA channel using osDmaChannelOpen(). 6. Create a DMA chain using osDmaChainCreate(). • Chain is created using allocated memory, a parameter structure, and a DMA controller handle. 7. Add DMA transfers to the DMA chain using osDmaChainTransferAdd() or osDmaChainTransferAddEx(). • osDmaChainTransferAddEx() returns a handle to added transfers; this allows for attribute modification. Runtime Follow these steps to run DMA in the application. 1. Reset or empty the DMA chain using osDmaChainReset(dma_chain). 2. Program the DMA channel with the DMA chain using status = osDmaChannelBind(dma_channel, dma_chain); SmartDSP OS User Guide 107
  • 108. Drivers Direct Memory Access (System DMA) NOTE DMA channel and chain must be unbound when executing function, status = osDmaChannelBind(dma_channel, dma_chain); If, however, an application reprograms the DMA channel with the same DMA chain then these conditions must be met: – DMA chain parameter must be NULL. – DMA channel must be bound using the following: status = osDmaChannelBind(dma_channel, NULL); 3. Start the DMA channel, after it is bound to a chain, using osDmaChannelStart(). 4. [Option] Poll a DMA channel using osDmaChannelIsActive() to check if the channel is active. – After completion of the DMA run and chain, the driver disables the interrupt. – Driver can be enabled at osDmaChannelOpen(). – If the interrupt was enabled, the driver calls the interrupt handler with interrupt parameters specified in OsDmaChannelOpen(). Free Follow these steps to enable DMA Free. 1. Ensure DMA channel is inactive. 2. Unbind DMA channel and chain using the function, osDmaChannelUnbind(). • Indicates DMA chain can be deleted or bound to a different DMA channel. • Indicates DMA channel can be closed or bound to a different DMA chain. 3. Release DMA channel using osDmaChannelClose(). • Releases all DMA channel resources (except memory) that belong to a user application. 4. Release DMA chain using osDmaChainDelete(). • Releases all DMA channel resources (except memory) that belong to a user application. Performance Rules Performance Rules guidelines—for user applications—improve MSC814x and MSC815x System DMA performance. • Place BD close to Port A (one of two ports). – Port A is always used for BD fetch. – Rule is primarily applicable to MSC8144. 108 SmartDSP OS User Guide
  • 109. Drivers OCeaN DMA • Minimize WAR penalties on the SoC CLASS fabric. – Application should configure the System DMA to read from a port close to the data source and write to the other port. – Rule is primarily applicable to MSC8144. • Consider target-switching when programming channels to access various targets. • Set BTSZ to the 64-byte maximum as part of the BD attribute. • Set TSZ to ‘high’ as per application requirements. Source Code SmartDSP OS DMA driver header files: • includecommonos_dma.h. • includearchstarcoremsc815xmsc815x_dma.h • initializationarchmsc815xincludemsc815x_dma_init.h • includearchstarcoremsc814xmsc814x_dma.h • initializationarchmsc814xincludemsc814x_dma_init.h Resource Management Minimize a driver’s data footprint by assigning channels-to-cores at compilation time. • Driver configures the master core (osGetMasterCore()) to handle error interrupts during osDmaInitialize() execution. • Driver handles HW-related errors. • User callback functions handle functional errors. Demo Use Cases SmartDSP OS DMA driver demos: • demosstarcoremsc814xdma_multicore • demosstarcoremsc815xdma_demo. OCeaN DMA OCeaN DMA, also known as OCN DMA and On-chip Network DMA, is used to generate RapidIO and PCIe (MSC815x only) buses. SmartDSP OS User Guide 109
  • 110. Drivers OCeaN DMA Features SmartDSP OS OCeaN DMA features are noted below. • OCeaN DMA is used to generate DMA accesses in the OCeaN fabric. – OCeaN fabric is a non-blocking, high-speed interconnect used for embedded system devices. • Able to generate transactions towards HSSI peripherals (sRIO and PCIe). • Accesses OCeaN ports as per address ranges configured in its ATMU windows. • Generates accesses in a 36-bit address space. – Relies on the target OCean ATMU mechanism to resolve the actual address. • Address space limitations: – System (CLASS): 32 bits. System interface shortens four MSB; it does not resolve addresses. – RapidIO: 34 bits. sRIO ATMU converts a 36-bit OCeaN address to a 34-bit sRIO address. – PCIe (MSC815x only). PCIe ATMU can convert a 36-bit OCeaN address to either a 32- or 64-bit PCIe address. • MSC814x supports a 34-bit ATMU bypass address space. – Makes write access part of the transfer description. – MSC815x has no HW support for ATMU address bypassing. Relevant SoC MSC8144 MSC815x Architecture This section covers the SW architecture of the OCeaN DMA driver. The OCeaN fabric requires no programming and provides a seamless interface for the HSSI. See OCean DMA ArchitectureOCean DMA ArchitectureTable 4.6. 110 SmartDSP OS User Guide
  • 111. Drivers OCeaN DMA Table 4.6 OCean DMA Architecture Processor Description MSC8144 • One OCeaN DMA instantiation. • Also called sRIO DMA. • Only supports sRIO. MSC815x • Two OCeaN DMA instantiations. • Support sRIO and PCIe. NOTE System DMA cannot be used to create transactions over I/O ports. Design Decisions Design decisions, along with their reasoning, are noted below. OCeaN and System DMA channels share two design decisions. 1. OCeaN DMA driver does not support cycle consuming cache and virtual addressing operations in the LLD. • Driver was written to minimize runtime overhead. • Driver API enables runtime modifications of pre-programmed BDs. 2. Assigning channels-to-cores occurs at compilation time. • Minimizes the driver’s program memory footprint. Calling Sequence Example Table 4.7 describes functions included in the SmartDSP OS OCeaN driver. The functions include kernel bring-up, application bring-up, application runtime, and application teardown. SmartDSP OS User Guide 111
  • 112. Drivers OCeaN DMA Table 4.7 OCeaN DMA API State Function Description os_config.h file #define • [MSC814x] OCeaN MSC814X_SRIO_DMA ON DMA support #define • [MSC815x] OCeaN MSC815X_OCN_DMA0 ON DMA support #define MSC815X_OCN_DMA1 ON Kernel Bring-up osInitialize()-> • User application does osArchDevicesInitializ not directly call these e()-> functions. ocnDmaInitialize() • osInitialize() calls the noted functions based on os_config.h defines and msc81xx_config.c configuration structures. • Initializes the OCeaN DMA driver. Application Bring-up ocnDmaControllerOpen() • Must be first function called. • Returns an OCeaN DMA controller handle; handle is a parameter in calling other functions. ocnDmaChannelOpen() • Opens a pre- allocated channel. • Initializes channel structure as per configuration parameters. ocnDmaChainCreate() • Creates an OCeaN DMA chain. • Initializes chain structure as per configuration parameters. ocnDmaChainTransferAdd • Adds a transfer to an () OCeaN DMA chain. 112 SmartDSP OS User Guide
  • 113. Drivers OCeaN DMA Table 4.7 OCeaN DMA API (continued) State Function Description Application Runtime ocnDmaChannelBind() • Binds a chain to a channel. ocnDmaChannelStart() • Starts execution of a bound chain(s) on an OCeaN DMA channel. ocnDmaChannelIsActive( • Polls the OCeaN ) DMA channel to check its state (active/ idle). ocnDmaTransferWait() • Waits for the release of a specific OCeaN DMA channel. Application ocnDmaChainDelete() • Releases OCeaN Teardown DMA chain resources (except memory). • Removes a chain from the OCeaN DMA controller. ocnDmaChannelClose() • Releases OCeaN DMA channel resources (except memory). Functionality Figure 4.2 shows an MSC8156 HSSI block diagram and illustrates the role of OCeaN DMA. SmartDSP OS User Guide 113
  • 114. Drivers OCeaN DMA Figure 4.2 MSC815x HSSI Block Diagram Source Code SmartDSP OS OCeaN DMA MSC814x and MSC815x driver header files for initialization and runtime: • initializationarchmsc814xincludemsc814x_srio_dma_init .h • includearchstarcoremsc814xmsc814x_srio_dma.h • initializationarchmsc815xincludemsc815x_ocn_dma_init. h • includearchstarcoremsc815xmsc815x_ocn_dma.h Demo Use Cases demosstarcoremsc814xrio_dma demosstarcoremsc815xrio_dma 114 SmartDSP OS User Guide
  • 115. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) QUICC Engine Unified Ethernet Controller (QE UEC) Introduction The MSC814X and MSC815X QE controllers support two GETH UECs. Each controller supports several standard MAC-PHY interfaces that connect to an external Ethernet transceiver. Features Smart DSP OS System QE UEC features are noted below: • Packet filtering: – QE selects the target queue. – [Default] Packets are filtered and classified to queues as per MAC addresses. • Extended filtering and pattern matching options: – User overrides default filtering during initialization or runtime. – Driver configures the UEC to filter as per set patterns or packet fields; e.g., IP address. – Applications provide additional runtime rules. • G/ETH UEC: – Default configuration for Ethernet support. – Override with uec_eth_params_t structure during UEC initialization. – MSC814x and MSC815x QE support two GETH UECs. • Controllers: – Support several standard MAC-PHY interfaces connecting to an external ETH transceiver. – Have different UEC drivers. – Run at HW supported speeds and protocols (e.g., 1000Mbps SGMII, 100Mbps RGMII). • Drivers: – Supports a maximum of eight Tx and Rx queues. – UEC HW and drivers support two behaviors (single- and multi-buffered frames) that handle incoming packets with a payload larger than the QE-programmed MTU. SmartDSP OS User Guide 115
  • 116. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) • Queue scheduling policy: – Driver enables configuring of UEC queues. – Supported scheduling policies: Strict Priority and Weighted Fair Queueing. – Channels/queues are prioritized and classified as per application requirements. – Configuration done at initialization or runtime. • UEC single-buffered frames: – [Default] Enables UEC single-buffered frames. – Functions defined at compilation time. – All packet contents must be placed in a single buffer; only one BD points to this buffer. The BD passes packet information from HW to SW. – Buffer memory must have a maximum payload size. – Provides fast LLD and BIO execution. • UEC multi-buffered frames: – Functions are defined at compilation time. – Enable by setting definitions in the os_config.h at compilation time: #define UEC0_MULTI_BUFFERED_FRAME #define UEC1_MULTI_BUFFERED_FRAME – Fewer memory restrictions as buffer memory isn’t needed to achieve maximum payload size. – Slower LLD/BIO execution. – Requires SmartDSP OS multi-buffered frames. – Allows for SmartDSP OS multi-buffered frames; however, faster executing SmartDSP OS single-buffered frames are preferrable. • UEC configuration modes: – UEC supports several modes that are configured using flags passed in the initialization strcuture: – UEC_CFG_LOOPBACK - UEC is configured to loopback mode. – UEC_CFG_ENABLE_STATISTICS - UEC gathers runtime statistics. – UEC_CFG_LOSSLESS_FLOW_CONTROL - Enables lossless-flow-control. – UEC_CFG_FORCE_LINK - osInitialize functions even without a connection. • Callback function functionality: – Enables direct and easy access to the net stack. • Asymmetric buffering on different UEC: – Identical buffering (single or multi) is not required for UEC0 and UEC1. 116 SmartDSP OS User Guide
  • 117. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) NOTE See Hardware Abstraction Layers (HAL) for detailed BIO information. Relevant SoC SmartDSP OS Ethernet drivers support 8156 and 8144 Tx and Rx channels. Architecture This section covers the SW architecture of the UEC driver. Components This section details driver components found in the SmartDSP OS. Table 4.8 QE UEC Components Components Description Tx/Rx Queues • Each UEC driver supports up to 8 Tx and 8 Rx queues modelled as a unidirectional software channel. • Queues provide filtering and scheduling capabillities. UEC Device Control • UEC driver has device controls; they configure and change the state of the UEC and other device operations. • User calls the BIO abstraction layer that, in turn, calls uecCtrl() for the LLD. UEC_CMD_ENABLE Enable UEC. UEC_CMD_TX_RESTART Resume UEC Tx operation. UEC_CMD_ENTER_PATTERNS Pattern match programming. UEC_CMD_ADD_MCAST_ADDRES Add address to UEC S extended filtering. UEC_CMD_CONFIG_SCHEDULER Configuration of UEC scheduler. UEC_CMD_STAT_GET Receive UEC-gathered statistics. SmartDSP OS User Guide 117
  • 118. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) Design Decisions Design decisions, along with their reasoning, are noted below. 1. Each SW Tx and Rx channel is modelled as a unidirectional queue with filtering and scheduling capabilities. 2. Driver implementation provides callback function functionality. • Enables easy access to the net stack. 3. Driver is implemetned under the BIO abstraction layer. • User application calls BIO functions directly and UEC functions indirectly. • Creates certain uniformity among user applications; e.g., user must use the os_frame_t structure. Data Flow UEC driver supports both Rx (interrupt/polling) and Tx indications and can work in cooperation with the net stack. Transmit Flow If there is no interrupt then, after transmission, the previous Tx BD is checked for reuse. 1. Driver receives a frame transmitted from the BIO layer; the frame has a pointer (to a buffer). 2. Driver places the buffer on the BD ring. 3. If the buffer is transmitted successfully then the driver releases the frame—unless there is a user-defined callback. Recieve Flow BIO Rx channel callback function can be set to etherInput()— a network stack input point. If the LLD channel is open then a user application can affect each Rx BD (in the BD ring). 1. QE—upon receiving data—fills a buffer/s according to data size. 2. BD ring status bit signals the driver that data was received (by polling or interrupt). 3. Driver receives a signal then BIO takes a new buffer from the pool to replace a used buffer. 4. Driver calls BIO to create a frame for the used buffer. 5. Frame is created; user callback function is called via the BIO Rx callback. NOTE See Hardware Abstraction Layers (HAL) for information about frames and frame pools. 118 SmartDSP OS User Guide
  • 119. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) Programming Model This section covers driver bring-up—first by the OS, then by the application-chosen API. The API of the UEC driver handles initialization and control command functionality. General The UEC driver is implemented under the BIO abstraction layer. • User calls BIO methods to indirectly activate UEC driver methods. • BIO methods recieve UEC parameters; e.g., flags and structures. • Parameters are passed to the LLD. Table 4.9 details SoC configuration file structures; e.g., msc815x_config.c. msc815x_uec_init_params_t includes all the structures noted between the typedef struct brackets. typedef struct { uint8_t uec_id; uint32_t uec_base; uec_if_t uec_if; uint32_t config_flags; os_hwi_priority irq_priority; uint16_t max_tx_bd_ring_len; uint16_t max_rx_bd_ring_len; uint16_t max_rx_buf_len; uint8_t num_tx_bd_rings; uint8_t num_rx_bd_rings; uec_num_of_threads_t num_tx_threads; uec_num_of_threads_t num_rx_threads; bool file_by_mac_address; uec_filter_t *filters; uec_eth_params_t *eth_params; } msc815x_uec_init_params_t; SmartDSP OS User Guide 119
  • 120. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) Table 4.9 SoC Configuration File Structures Structure Description uint8_t uec_id UEC device index (zero based). uint32_t uec_base Base address of UEC memory map. uec_if_t uec_if Ethernet physical interface type. uint32_t config_flags UEC configuration flags (UEC_CFG_x). os_hwi_priority irq_priority IRQ prioritization of UEC interrupts. uint16_t max_tx_bd_ring_len Maximum Tx BD ring length. uint16_t max_rx_bd_ring_len Maximum Rx BD ring length. uint16_t max_rx_buf_len • Maximum buffer length for Rx rings; multiple of 128. • Same value for all the rings. uint8_t num_tx_bd_rings Number of Tx BD rings (queues). uint8_t num_rx_bd_rings Number of Rx BD rings (queues). uec_num_of_threads_t num_tx_threads Number of QE Tx threads. uec_num_of_threads_t num_rx_threads Number of QE Rx threads. bool file_by_mac_address If FALSE, • user is responsible for filing frames; • done by supplying a filter array and patterns. uec_filter_t *filters Sets to FALSE, • a filter array used for pattern matching in file_by_mac_address. uec_eth_params_t *eth_params • Pointer to Ethernet parameters • NULL will use defaults. Table 4.10 details a structure defined per UEC channel (BD ring). The structure defines main characteristics and configurations. 120 SmartDSP OS User Guide
  • 121. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) uec_channel_params_t includes all the structures noted between the typedef struct brackets. typedef struct { uint32_t addr_high32; uint16_t addr_low16; uint16_t bd_ring_len; bool interrupt_en; uint8_t coherency_en; os_mem_type heap; uint16_t lossless_flow_control_threshold; } uec_channel_params_t; Table 4.10 UEC Channel (BD ring)-defined Structure Structure Description uint32_t addr_high32 32-bits (high) of the MAC address channel. uint16_t addr_low16 16-bits (low) of the MAC address channel. uint16_t bd_ring_len Length of BD ring. bool interrupt_en • Tx channel: If TRUE, confirm transmitted frames upon interrupt. • Rx channel: If FALSE, process received frames by polling (without Rx interrupt). uint8_t coherency_en • Tx channel: If TRUE, flushes frame from cache before transmit. • Rx channel: If TRUE, invalidates frame before receive (buffers must be in system area only). os_mem_type heap Heap used for channel BDs. uint16_t LossLess flow control threshold. lossless_flow_control_threshold SmartDSP OS User Guide 121
  • 122. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) Table 4.11 details command definitions used to control a UEC device or channel. osBioDeviceCtrl() and osBioChannelCtrl() are called, respectively. In some cases, additional parameters are required. Table 4.11 UEC Commands Command Description UEC_CMD_ENABLE • Enables UEC operation. bdsaq UEC_CMD_TX_RESTARTBIO_DEVIC • Resume Tx operation. E_TX_ENABLE • Param: NULL UEC_CMD_RX_RESTARTBIO_DEVIC • Resume Rx operation. E_RX_ENABLE • Param: NULL UEC_CMD_TX_STOPBIO_DEVICE_T • Stop Tx after current frame. X_DISABLE • Param: pointer to uec_stop_params_t UEC_CMD_RX_STOPBIO_DEVICE_R • Stop Rx after current frame. X_DISABLE • Param: pointer to uec_stop_params_t UEC_CMD_ADD_MCAST_ADDRESS • Add address to UEC extended filtering. • Param: ip address UEC_CMD_REMOVE_MCAST_ADDR • Remove address from UEC ESS extended filtering. • Param: ip address UEC_CMD_TX_ON_DEMAND • Cause an immediate Tx when in polling mode. • Param: NULL UEC_CMD_TX_PAUSE • Transmit a Pause frame. • Param: pointer to uec_pause_params_t UEC_CMD_TX_RESUME • Transmit a flow control "Resume" frame. • Param: NULL UEC_CMD_TX_HDFC_START • Start half-duplex flow control for Tx. • Param: NULL UEC_CMD_TX_HDFC_STOP • Stop half-duplex flow control for Tx. • Param: NULL 122 SmartDSP OS User Guide
  • 123. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) Table 4.11 UEC Commands Command Description UEC_CMD_INT_ENABLE • Unmask specified interrupts. • Param: uint32_t combining UEC_INTR_x values UEC_CMD_INT_DISABLE • Mask specified interrupts. • Param: uint32_t combining UEC_INTR_x values UEC_CMD_STAT_GET • Get statistics data. • Param: pointer to uec_statistics_t* UEC_CMD_STAT_RESET • Reset statistics counters. • Param: NULL UEC_CMD_ADDITIONAL_TX_STAT_ • Get additional Tx statistics data. GET • Param: pointer to uec_additional_tx_statistics_t* UEC_CMD_ADDITIONAL_RX_STAT_ • Get additional Tx statistics data. GET • Param: pointer to uec_additional_rx_statistics_t* UEC_CMD_ENTER_PATTERNS • Program the pattern matching mechanism. • Param: pointer to uec_filing_params_t UEC_CMD_PHY_REG_WRITE • Write to a PHY register via MII. • Param: pointer to uec_phy_access_t UEC_CMD_PHY_REG_READ • Read from a PHY register via MII. • Param: pointer to uec_phy_access_t UEC_CMD_UTFTT_REG_WRITE • Modify the UTFTT register value. • Param: new value UEC_CMD_CONFIG_SCHEDULER • Configure a scheduler queue scheduling policy. • Param: pointer to uec_scheduler_config_params_t UEC_CMD_ADD_MAC_ADDRESS • Add MAC address to UEC. • Param: pointer to MAC address SmartDSP OS User Guide 123
  • 124. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) Table 4.11 UEC Commands Command Description UEC_CMD_REMOVE_MAC_ADDRES • Remove MAC address from the S UEC. • Param: pointer to MAC address UEC_CMD_RX_POLL • Process received frames when Rx interrupt is disabled. • Param: NULL UEC_CMD_TX_CONFIRM • Confirm transmitted frames. • Param: NULL UEC_CMD_DBG_PRINT_ALLOC_TXB • Allocate Tx BD buffers for Debug DBUF Print feature. • Param: length of Tx BD data buffer. UEC_CMD_DBG_PRINT_TX_BDINIT • Initialize Tx BD buffer for Debug Print Tx channel. • Param: buffer length, buffer Calling Sequence Example Table 4.12 lists functions included in the UEC driver API. 124 SmartDSP OS User Guide
  • 125. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) Table 4.12 QE UEC API Flow Stage Name Description Kernel Bring-up osInitialize() -> • User application osArchDevicesInitialize() indirectly calls these -> functions. qeInitialize() • osInitialize() calls qeInitialize(); os_config.h and msc81xx_config.c contain definitions and configuration structures. • osInitialize() initializes the OS and calls function osArchDevicesIni tialize()to initialize the architecture and all application-required devices. • osArchDevicesInit ialize() calls qeInitialize() to initialize the QE. osInitialize() -> • osInitialize() osArchDevicesInitialize() calls -> osArchDevicesIni tialize() which, in uecInitialize() -> turn, calls bioRegister() uecInitialize(); latter initializes the UEC driver. • uecInitialize() calls bioRegister() to take and register the driver to the BIO abstraction layer. • bioRegister() returns the BIO device handle; LLD uses it for BIO calls to this device. SmartDSP OS User Guide 125
  • 126. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) Table 4.12 QE UEC API (continued) Flow Stage Name Description Application Bring- osBioDeviceOpen() -> • osBioDeviceOpen() up uecOpen() opens a BIO device for operation. • Uses given parameters and returns a BIO device handle. • Calls uecOpen() to get a handle to the UEC HW. osBioChannelOpen() -> • osBioChannelOpen( uecChannelOpen() ) opens a BIO device channel. • Calls uecChannelOpen() to get a handle to the UEC queue. Application osBioChannelTx() -> • osBioChannelTx() Runtime uecMbfChannelTx() or transmits a frame via a BIO channel uecSbfChannelTx() previously opened for transmission. • Calls uecMbfChannelTx( ) or uecSbfChannelTx( ). osBioDeviceCtrl() -> • osBioDeviceCtrl() uecCtrl() performs control commands on a device. • Calls uecCtrl(). • uecCtrl() performs a predefined device- level control; e.g., adding a filter. osBioChannelCtrl() -> • osBioChannelCtrl( uecChannelCtrl() ) performs control commands on a channel and calls uecChannelCtrl() . • uecChannelCtrl() performs a predefined channel-level control; e.g., poll for received frames. 126 SmartDSP OS User Guide
  • 127. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) Table 4.12 QE UEC API (continued) Flow Stage Name Description uecMbfTxIsr() • Calls an interrupt service routine. • Occurs when a packet—configured to issue an interrupt— has been sent, and the UEC multi- buffered frame mechanism is enabled. uecSbfTxIsr() • Calls an interrupt service routine. • Occurs when a packet—configured to issue an interrupt— has been sent, and the UEC multi- buffered frame mechanism is disabled (default). uecMbfRxIsr() • Calls an interrupt service routine. • Occurs when a packet—configured to issue an interrupt— has been received, and the UEC multi- buffered frame mechanism is enabled. uecSbfRxIsr() • Calls an interrupt service routine. • Occurs when a packet—configured to issue an interrupt— has been received, and the UEC multi- buffered frame mechanism is disabled (default). Functionality This section details initialization. SmartDSP OS User Guide 127
  • 128. Drivers QUICC Engine Unified Ethernet Controller (QE UEC) Initialization QE handles all controller traffic therefore the QE and controllers must be initialized at the SoC-level. 1. QE initialization header file: initialization/arch/msc81xx/include/qe_init.h 2. UEC initialization header file: initialization/arch/msc81xx/include/msc81xx_uec_init.h 3. Enable individual UECs at os_config.h by setting the macros to ON: #define MSC81XX_UEC0 ON #define MSC81XX_UEC1 ON 4. Function uecInitialize() is responsible for the following: • Initializes UEC based on the msc81xx_config.c structure of msc81xx_uec_init_params_n. • Calls initEtherPhy(), a BSP callback function for initializing the board. If not implemented, a link time error will occur. Source Code UEC driver header files: Table 4.13 UEC Header Files File Source Type Details MSC814x Initialization smartDSPinitializationarchmsc814xincludemsc 814x_uec_init.h Runtime smartDSPincludearchstarcoremsc814xmsc81 4x_uec.h MSC815x Initialization smartDSPinitializationarchmsc815xincludemsc 815x_uec_init.h Runtime smartDSPincludearchstarcoremsc815xmsc81 5x_uec.h Demo Use Cases UEC driver demos: • demosstarcoremsc815xnet_demo • demosstarcoremsc815xnet6_demo • demosstarcoremsc815xnet_ip4_ip6_demo 128 SmartDSP OS User Guide
  • 129. Drivers Serial RapidIO (sRIO) • demosstarcoremsc815xnet_mbf • demosstarcoremsc815xuec_multicore NOTE Additional demos can be found in the SmartDSP release layout. Serial RapidIO (sRIO) Introduction Serial RapidIO(R) (sRIO) is a point-to-point, packet-based, switched-system, interconnect technology. sRIO provides high performance and bandwidth as well as faster bus speed interconnect technology. sRIO is an intra-system interface that provides chip-to-chip and board-to-board communication at GBps performance levels.It was developed to control data and signal plane applications of large-scale embedded systems. RIO is characterized by the following: • One or two hosts but up to 65,534 agents. • Agents can scan and exchange data in the system. • RIO agents are connected via RIO switches. The RIO standard defines multiple transaction types: Table 4.14 RIO Transaction Types Transaction Description Module Applications Direct I/O Writes to destination Modules can work memory. simultaneously. Doorbell Short (2 bytes) messages • Bus: specifies the address from source to destination. space going to the SRIO Messaging Transfers a message (max. 4 interface. KB) from source to • Packet: destination. exchanges messages Maintenance • Standard or between SRIO Accesses implementation- agents. specific registers in a destination’s • Doorbell: RIO address messages space. contain 16-bit information, • Port-Write: passes source ID, and error information. destination ID. SmartDSP OS User Guide 129
  • 130. Drivers Serial RapidIO (sRIO) Features A sRIO driver supports the following RIO transaction types: Table 4.15 RIO Transaction Types Transaction Description Type5 RIO NWRITE Type6 RIO SWRITE Type8 RIO Maintenance OCeaN DMA Direct access ATMU Bypass MSC814x supports small system maintenance. ATMU MSC815x supports small & large system maintenance. Relevant SoC SmartDSP OS sRIO drivers support MSC814x and MSC815x devices; see Table 4.3. Table 4.16 SoC RIO Support Support Description Direct I/O • Supported by OCeaN DMA (in the HW). • Programmable via the following: – Standard SmartDSP OS DMA API channels, chains, and transfers – Direct access to OCeaN DMA Maintenance • Supported by demosstarcoremsc815xuart. – MSC814x supports small systems maintenance using ATMU bypass. Maintenance access is generated using srioDmaMaintenanceAccess(). – MSC815x supports maintenance in small and large systems using ATMU. Architecture This section covers the SW architecture of the system sRIO driver. 130 SmartDSP OS User Guide
  • 131. Drivers Serial RapidIO (sRIO) Components This section details sRIO driver components. Table 4.17 sRIO Driver Components Component Description Controller • Represents the HW block. • 34-bit address support. • I/O ATMU windows. SRIO Window ATMU window for I/O type 5/6 transactions. Maintenance ATMU ATMU window for maintenance transactions. Port Represents the HW port. Data Flow This section outlines transaction and maintenance data flows. NWRITE and SWRITE transaction flows: 1. Application pre-configures I/O windows. 2. Application writes data to the outbound ATMU window address space. 3. MSC814x OCN DMA transfers: a. [Optional} For MSC8157 b. [Mandatory] For sRIO transaction over MSC8156_FAMILY—executed with the OCN DMA API. Maintenance data flow: 1. Open maintenance ATMU. 2. Write data via SRIO maintenance access procedure. 3. Close maintenance ATMU. Programming Model This section covers driver bring-up—first by the OS, then by the application-chosen API. General The sRIO driver API has the following functionality: • write transactions SmartDSP OS User Guide 131
  • 132. Drivers Serial RapidIO (sRIO) • maintenance accesses • sRIO generic See the SmartDSP OS API Reference Manual for a complete list of sRIO LLD API. Table 4.18 describes the MSC815x driver API in light of driver functionality. NOTE For the MSC814x API, replace the function prefix ocnDMA with srioDMA. Table 4.18 Functionality Perspective of MSC815x API Functionality API Functions Description Write Transactions • srioOutboundWindowO I/O window pen management. • srioOutboundWindowFi nd • srioOutboundWindowFr ee • srioOutboundWindowE nable • srioOutboundWindowDi sable • srioInboundWindowOp en • srioInboundWindowFin d • srioInboundWindowFre e • srioInboundWindowEn able • srioInboundWindowDis able 132 SmartDSP OS User Guide
  • 133. Drivers Serial RapidIO (sRIO) Table 4.18 Functionality Perspective of MSC815x API Functionality API Functions Description Maintenance API • srioMaintenanceAtmuO Maintenance access pen management. • srioMaintenanceAtmuF ree • srioMaintenanceAcces s • srioMaintenanceTarget Set sRIO Generic API • srioRecover sRIO management and • srioClearPortErrors controls. • srioAlternateIdSet • srioAlternateIdDisable • srioAcceptAllConfigur e • srioDeviceAdd Calling Sequence Example Table 4.19 lists functions included in the write transactions API of the SmartDSP OS MSC8156_FAMILY sRIO driver. Functions include kernel bring-up, application bring- up, application runtime, and application teardown. SmartDSP OS User Guide 133
  • 134. Drivers Serial RapidIO (sRIO) Table 4.19 N/SWRITE Transactions API State Function Description Kernel Bring-up osInitialize() -> • User application archDeviceInitialize() indirectly calls -> these functions. srioInitialize() • osInitialize() calls oInitialize()— as based on os_config.h defines and msc81xx_config.c configuration structures. • Initializes sRIO driver. • Opens ATMU I/O windows. • Enables I/O windows. • Initializes sRIO system on the ADS. Application Bring-up ocnDmaControllerOpen() • Must be first function called. • Returns an OCN DMA controller handle. • Handle is a parameter in calling other functions. ocnDmaChannelOpen • Opens a pre- allocated channel. • Initializes channel structure as per configuration parameters. ocnDmaChainCreate • Creates an OCN DMA chain. • Initializes chain structure as per configuration parameters. ocnDmaChainTransferAdd • Adds a transfer to the OCN DMA chain. 134 SmartDSP OS User Guide
  • 135. Drivers Serial RapidIO (sRIO) Table 4.19 N/SWRITE Transactions API State Function Description Application Runtime ocnDmaTransfer • Performs a transfer & transaction starts. ocnDmatransferAdd • Adds a transfer to a chain. ocnDmaChannelBind • Binds a chain to a channel. ocnDmachannelStart • Starts transaction. Application Teardown ocnDmaChannelUnbind • Unbinds chain from a channel. ocnDmaChannelClose • Frees OCN DMA channel. Table 4.20 lists functions included in the maintenance transactions API of the SmartDSP OS MSC8156_FAMILY sRIO driver. The functions include kernel bring-up, application bring-up, application runtime, and application teardown. SmartDSP OS User Guide 135
  • 136. Drivers Serial RapidIO (sRIO) Table 4.20 MAINTENANCE Transactions API Table 4.21 State Function Description Kernel Bring-up osInitialize() -> • User application archDeviceInitialize() -> indirectly calls these functions. srioInitialize() • osInitialize() calls oInitialize()— as based on os_config.h defines and msc81xx_config.c configuration structures. • Initializes sRIO driver. • Initializes sRIO system on the ADS Application ocnDmaControllerOpen() • Must be first function Bring-up called. • Returns an OCN DMA controller handle. • Handle is a parameter in calling other functions. ocnDmaChannelOpen • Opens a pre- allocated channel. • Initializes channel structure as per configuration parameters. srioMaintenanceAtmuOpen • Opens ATMU window for RIO maintenance. Application srioMaintenanceAccess • Executes Runtime maintenance access (W/R). Application srioMaintenanceAtmuClose • Frees a maintenance Teardown ATMU window. ocnDmaChannelClose • Frees an OCN DMA channel. Functionality The below description provides information for operating data transactions over sRIO. 136 SmartDSP OS User Guide
  • 137. Drivers Serial RapidIO (sRIO) Initialization Follow these steps to initialize data transaction functionality over the sRIO driver: 1. Enable sRIO support in the application os_config.h file by setting #define MSC81XX_SRIO ON. 2. Enable OCN DMA support in the application os_config.h file by setting #define MSC81XX_OCN_DMAx ON. 3. Allocate memory—enables driver to handle an OCN DMA channel. 4. Allocate memory for a OCN DMA chain handle. 5. User application determines DMA chain parameters. 6. Get an OCN DMA controller handle using osDmaControllerOpen(). • Function returns the handle to the driver-allocated OCN DMA controller. • User application retrieve this handle to open OCN DMA channels and create OCN DMA chains. 7. Create an OCN DMA chain using ocnDmaChainCreate(). 8. Add DMA transfers to the DMA chain using ocnDmaChainTransferAdd() or ocnDmaChainTransferAddEx(). • ocnDmaChainTransferAddEx() returns a handle to added transfers; this allows attribute modification. Runtime Follow these steps to run sRIO in the application: 1. Bind the OCN DMA channel with a chain using ocnDmaChannelBind(). 2. Start the OCN DMA transaction using ocnDmaChannelStart(). 3. Poll a channel to check if it is active using ocnDmaChannelIsActive(). Free Follow these steps to free OCN DMA: 1. Ensure OCN DMA channel is inactive. 2. Unbind DMA channel and chain using the function, osDmaChannelUnbind(). • Indicates DMA chain can be deleted or bound to a different DMA channel. • Indicates DMA channel can be closed or bound to a different DMA chain. 3. Release DMA channel using osDmaChannelClose(). • Releases all DMA channel resources (except memory) belonging to a user application. 4. Release DMA chain using osDmaChainDelete(). SmartDSP OS User Guide 137
  • 138. Drivers Doorbell • Releases all OCN DMA channel resources (except memory) belonging to a user application. Source Code SmartDSP OS sRIO driver header files: • includearchstarcoremsc815xmsc815x_srio.h • initializationarchmsc815xincludemsc815x_srio_init.h • includearchstarcoremsc814xmsc814x_srio.h • initializationarchmsc814xincludemsc814x_srio_init.h Resource Management Minimize driver data footprints by assigning OCN DMA channels-to-cores at compilation time. • Driver configures the master core (osGetMasterCore()) to handle errors during srioInitialize() execution. • Driver handles HW-related errors. • User callback functions handle functional errors. Demo Use Cases demosstarcoremsc815xrio_dma demosstarcoremsc814xrio_dma Doorbell Introduction RapidIO (R) type10 traffic, also known as doorbells; is used to pass a short message (2 bytes) from one endpoint to another. Generally it is used to pass control information. Features The sRIO doorbell driver has the following features: • Enabled by setting it to ‘ON’ in the os_config.h file using #define MSC81XX_DOORBELL ON. • Generates short messages in which 16 bits are reserved as part of the header. 138 SmartDSP OS User Guide
  • 139. Drivers Doorbell • Runs only in the master core. Relevant SoC MSC8144 MSC815x Architecture Design Decisions User applications that share Rx doorbells among cores can consider these two approaches: • If the 16-bit doorbell information is important to all cores then the channel callback function generates and transmits an intercore message. • If only knowledge of the doorbell is important (versus the 16-bit information) then all cores (aside from the master) call osHwiCreate() and register themselves to the doorbell interrupt. NOTE The master core calls CIO functions thus only a single core manages the HW. Programming Model Calling Sequence Example Doorbell API The sRIO doorbell driver is a CIO. The architecture-dependant header file of the sRIO doorbell driver is includearchstarcoremsc81xxmsc81xx_doorbell.h. Table 4.22 lists various sRIO doorbell driver API functions. SmartDSP OS User Guide 139
  • 140. Drivers Doorbell Table 4.22 sRIO Doorbell Driver Status Name Description Kernel Bring-up osInitialize() -> • User application osArchDevicesInitialize() - does not directly > call these functions. srioInitialize() • osInitialize() calls srioInitializ e() based on os_config.h defines and msc81xx_confi g.c configuration structures. • Initializes sRIO driver. osInitialize() -> • osInitialize() osArchDevicesInitialize() - calls > doorbellIniti alize()to start doorbellInitialize() -> the doorbell cioRegister() driver. • cioRegister(): – registers the driver to the CIO abstraction layer. – returns a pointer to the CIO device handle. – LLD uses the pointer for CIO calls to this device. Application Bring- osCioDeviceOpen() -> • Must be first up doorbellOpen() function called. • Returns a CIO device handle. osCioChannelOpen() -> • Opens a pre- doorbellChannelOpen() allocated CIO device channel. • Initializes doorbell channel structure as per configuration parameters. 140 SmartDSP OS User Guide
  • 141. Drivers PCI Express (PCIe) Table 4.22 sRIO Doorbell Driver (continued) Status Name Description Application osCioChannelTx() -> • osCioChannelTx Runtime doorbellChannelTx() () transmits a frame via a previously opened CIO channel. • Calls doorbellChann elTx()to send a doorbell message. osCioDeviceCtrl() -> • osCioDeviceCtr doorbellChannelCtrl() l()performs control commands. • doorbellChanne lCtrl()perform s a channel-level controlling function. doorbellRxIsr() • Upon message receipt, generates a receive interrupt service routine. Demo Use Cases demosstarcoremsc814xdoorbell demosstarcoremsc815xemsg_doorbell demosstarcoremsc815xdoorbell PCI Express (PCIe) PCIe driver is implemented as part of SmartDSP OS drivers. MSI is an optional feature. A system-specified message written to a system-specified address enables a device to request service. For example, a PCI DWORD memory write transaction. The PCIe MSI driver supports PCIe MSI messages. Features Features include the following: SmartDSP OS User Guide 141
  • 142. Drivers PCI Express (PCIe) • Supported on MSC815x; connect to PCIe at EP or RC using the function pexlsRootComplex(). • Enable (ON)/Disable (OFF) PCIe driver support using macro MSC81XX_PEX in the SmartDSP OS configuration file (os_config.h). This section lists MSC815x PCIe MSI driver features: • Supports a maximum of eight message generations—each message generates a different virtual interrupt on the RC side. • EP implementation as per PCIe MSI standard. • MSI message sent via two implementations: – HW implementation that uses GCR5 pex_irq_out bit to trigger MSI generation. SW implementation that uses an outbound ATMU window to map a translated address to the MSI address. A write operation—containing MSI address with appropriate data values—to the ATMU window generates an MSI transaction to the remote RC. Relevant SoC MSC815x Architecture Components The below table details PCIe MSI driver components: Table 4.23 PCIe MSI Driver Components Component Description pex_msi_ep_init_t • Contains initialization parameters for msi_init_params the pexEpMsiInitialize() function. • EP initializes all pex_msi_ep_init_t.* parameters. 142 SmartDSP OS User Guide
  • 143. Drivers PCI Express (PCIe) Table 4.23 PCIe MSI Driver Components Component Description pex_msi_rc_init_t • Contains initialization parameters for msi_init_params the pexRcMsiInitialize() function. • RC initializes all pex_msi_rc_init_t.* parameters. pex_msi_handle_t msi_handle • Holds all relevant information following initialization using functions pexEpMsiInitialize() or pexRcMsiInitialize(). • pexEpMsiInitialize() execution allocates and updates msi_handle. • Thereafter, pass the handle to all PCIe MSI API functions. Design Decisions Design decisions relating to a multi-core environment are noted in the below table. Table 4.24 Multi-core Environment Design Decisions Environment Feature Description Multi-core EP • Each core acquires a Environment spinlock. • Spinlock is released at the end of an operation. • MSI message is sent. RC • Only the master core performs MSI EP initialization. SmartDSP OS User Guide 143
  • 144. Drivers PCI Express (PCIe) Table 4.24 Multi-core Environment Design Decisions Environment Feature Description HW Limitations VIGR • MSI standard indicates that the EP can modify the number of lower bits defined by the MME field but not message data. • MSC815x VIGR implementation has three VIRQ_NUM_L bits. • SmartDSP OS supports up to 8 (2^3) MSI messages. Endian Swap • MSI HW implementation that uses bit GCR5_PEX_IRQ_OUT triggers an MSI generation that causes MSI data to arrive Endian swapped. • May generate only virtual interrupt 0 as it always write zeros to the VIGR lower bits. Data Flow Transmit/Dispatch Flow On the EP, the pexMsiSend(msg_num) function triggers an MSI generation that asserts one RC virtual interrupt. Receive/Consume Flow During MSI initialization, the RC receive flow has two possible forms: • RC subscribes to a set of virtual interrupts and initializes EP message data as per existing virtual interrupts. • RC handles the virtual interrupt and uses hwi_arg to identify the sent message. 144 SmartDSP OS User Guide
  • 145. Drivers PCI Express (PCIe) Programming Model This section describes driver bring-up. SmartDSP OS User Guide 145
  • 146. Drivers PCI Express (PCIe) General Table 4.25 PCIe MSI Driver Functions Feature Functions Description RC os_status pexRcMsiInitialize • Activate on RC. • pci_dev_t *pci_dev • Creates virtual interrupts. • pex_msi_init_t *msi_params • Initializes all EP MSI fields then sets the • pex_msi_handle_t MSI Message Control *msi_handle Register (0x72) MSIE bit to ON. • Parameter pci_dev_t *pci_dev represents the EP device. EP Tos_status pexEpMsiInitialize • Activate on EP. • pex_msi_ep_init_t • Initializes *msi_params msi_handle. • pex_msi_handle_t • Polls MSI Message *msi_handle Control Register (0x72) MSIE bit. MSI os_status pexMsiSend • Sends MSI message using function • void * msi_handle, pexMsiSwSend() or uint8_t msg_num pexMsiHwSend(). • Function pointer, passed to the driver during initialization, selects the function. MSI os_status pexMsiSendFuncSet • Replaces send MSI function with a new • void * msi_handle, one. Ensure that the • pex_msi_send_function initialization parameters allow use send_func of both versions. • Necessary to set OCN DMA parameters to use pexMsiSwSend() function. 146 SmartDSP OS User Guide
  • 147. Drivers PCI Express (PCIe) Table 4.25 PCIe MSI Driver Functions Feature Functions Description MSI os_status pexMsiSwSend • Sends MSI message using a SW • void * msi_handle implementation. • uint8_t msg_num • Generate write transaction using OCN DMA and PCIe Outbound window. • Do not use this function directly. Instead, activate it by using the pexMsiSend() function. MSI os_status pexMsiHwSend • Sends MSI message using PEX_IRQ_OUT • void * msi_handle in GCR5. • uint8_t msg_num • EP initiates the transaction using GCR5 thus OCN DMA initialization parameters are not required. • Activate function indirectly using pexMsiSend(). Calling Sequence Example The table below lists RC and EP PCIe MSI driver functions. See General for function descriptions, excepting msiHwiIsr(). Table 4.26 Feature Function Description RC pexRcMsiInitialize() • RC is interrupted. • Dispatcher calls cmsiHwiIsr() for each incoming MSI. EP pexEpMsiInitialize() • Calls pexMsiSend()when an MSI should be sent to the RC. • Sends messages to the RC. SmartDSP OS User Guide 147
  • 148. Drivers PCI Express (PCIe) The user supplier ISR routine function, msiHwiIsr(), is activated when a virtual interrupt is asserted. Use the routine to check the message number and determine further actions. Functionality This section deals with EP and RC initialization and runtimes. EP Initialization Listing 4.1 shows EP initialization parameters and their specifications. Listing comments denote the following: • pexMsiHwSend() function usage might not initialize OCN DMA parameters. • If so, set msi_init_params.ocn_dma field to NULL. • Specifying these parameters does not effect runtime as they are not used in pexMsiHwSend(). Listing 4.1 EP Initialization /* For msi_handle allocation */ msi_init_params.heap = OS_MEM_LOCAL_NONCACHEABLE; msi_init_params.msi_send_func = pexMsiSwSend; /* Pex Outbound window base for pexMsiSwSend. * Outbound window is opened and closed by EP during the pexMsiSwSend*/ msi_init_params.out_win_base = (uint64_t)OUTBOUND_EP_BASE; /* OCN DMA parameters for windows opening, * if only pexMsiSendGCR5 function is used then ocn_dma should be NULL * and then there is no need to initialize any OCN DMA parameters */ msi_init_params.ocn_dma = ocn_dma; msi_init_params.dma_channel = dma_channel; msi_init_params.ocn_device_id = OCN_DMA_ID0; RC Initialization Listing 4.2 shows RC initialization parameters and their specifications. Listing comments denote the following: • Must always initialize all msi_init_params.*parameters. • msi_init_params.msi_mme field can get zero to three (0 to 3) values. • If msi_init_params.msi_mme = 0 then EP is unable to change message data; thereafter, all EP messages are sent as zero. Listing 4.2 RC Initialization /* For msi_handle allocation */ 148 SmartDSP OS User Guide
  • 149. Drivers PCI Express (PCIe) msi_init_params.heap = OS_MEM_LOCAL_NONCACHEABLE; /* Msi message address */ msi_init_params.msi_addr = MSI_BUS_ADDR; /* Priority for virtual interrupts */ msi_init_params.hwi_priority = OS_HWI_PRIORITY0; /* Enable 2^mme messages/interrupts */ msi_init_params.msi_mme = 0x3; /* Interrupt service routine */ msi_init_params.hwi_handler = msiHwiIsr; // VIGR = 0xFFF27000 /* RC should route the inbound window to the VIGR vector */ msi_init_params.in_win_translation = (uint64_t)&g_msc815x_ccsr- >gic.vigr; EP Runtime 1. Activates pexMsiSend(msg_num) in order to send messages. 2. If the RC allows only a single message (msi_mme = 0) then all msg_num are sent as zero. 3. If the RC allows more then one message during initialization, then the msg_num must be smaller than the maximum number of allowed messages. 4. If required, switch to another type of pexMsiSend() function using pexMsiSendFuncSet(). RC Runtime 1. Handles received interrupts. 2. Message numbers are received via the hwi_arg parameter. Resource Management The master core handles general PCIe interrupts: • Clears interrupts. See Interrupts for further information. • Activates user callback function. See demosstarcoremsc815xuart for PCIe traffic generation information. Demo Use Cases demosstarcoremsc815xpex_digital_loopback demosstarcoremsc815xpex_ep_msi demosstarcoremsc815xpex_rc_msi SmartDSP OS User Guide 149
  • 150. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) Multi Accelerator Platform Engine– Baseband (MAPLE–B/B2) Introduction MAPLE-B is a baseband, algorithm accelerator for Turbo, Viterbi, FFT/iFFT, DFT/iDFT, and CRC algorithms. MAPLE-B is a PSIF—a programmable controller with CRC accelerator and DMA capabilities. MAPLE-B2 is a multi-standard, baseband, algorithm accelerator for Channel Decoding/ Encoding, Fourier Transforms, UMTS chip-rate processing, OFDMA and SC-FDMA equalization, and CRC algorithms. MAPLE-B2 is a second generation PSIF (PSIF2)—a programmable controller with DMA capabilities. Features Features of the MSBA8100 and MSC815x family of MAPLE–B/B2 drivers are noted below. • Implemented as part of the SmartDSP OS drivers. • Complies with SmartDSP OS driver rules and API. • COP features: – Each processing element functions as a COP device. – MAPLE also acts as a COP device – Belongs to the COP LLD layer that manages jobs and queues. • Allows multiple hosts to share a single MAPLE–B/B2 device OR a single host to use multiple MAPLE–B/B2 devices. – Driver must identify the master host controlling the MAPLE–B/B2. – Each MAPLE must have a single master—more than one will cause an error. MAPLE–B/B2 goals: – Minimum overhead. – Seamless integratation of SoC bring-up code. – Support MSBA8100 and MSC815x family. – User will choose the configuration interface. – User dispatches multiple BDs in a single function call. 150 SmartDSP OS User Guide
  • 151. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) Relevant SoC MSBA8100 and MSC815x family. Architecture This section covers the SW architecture of MAPLE–B/B2 drivers. Components This section details MAPLE–B/B2 driver components found in the SmartDSP OS. See Table 4.27 for further details. Table 4.27 Maple–B/B2 Components Components Description COP Abstraction Layer COP module layer; see COP Module. Maple LLD Functions are activated via COP abstraction layer functions. Device • Processing element abstraction. • All relevant registers and parameters of a specific processing element are handled as follows: – unified under the device concept ; and, – initialized when opening the device. Channel • BD ring abstraction. • A channel, at any given time, can only contain a limited number of jobs: – each reaped job is removed from the channel; and, – ensures space for newly dispatched jobs. Job • BD abstraction. • Similar structure to the HW BD. Design Decisions Design decisions, along with their reasoning, are noted below. 3. Restricted channel usage—two different cores cannot open the same channel. • Driver was written to minimize runtime overhead. • Minimum mutual-exclusion locks. SmartDSP OS User Guide 151
  • 152. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) 4. Device-sharing—first core to open the device initializes all the registers and parameters; other cores will use the existing LLD device handle. • Support multicore usage of MAPLE–B/B2. • Support multicore usage of all processing elements. 5. During the MAPLE open device routine, each core subscribes to all MAPLE error interrupts. • Provide error handling and failure recovery mechanism. 6. Each channel can handle a limited (user-defined) number of jobs. • Allows driver to maintain the channel (for the user). • Allows driver to maintain the BD ring DRAM (for the user). Data Flow This section outlines the dispatch flow. Dispatch Flow Jobs are dispatched to the PE following correct channel initialization. Listing 4.3 outlines a structure for a NULL-terminated, linked, COP job dispatch list. The application, with a single function call, can dispatch multiple jobs to each PE. Listing 4.3 COP Job Dispatching typedef void* cop_job_id; typedef struct cop_job_handle_s { cop_job_id job_id; /**< Used by the application to identify finished jobs. */ void *device_specific; /**< LLD specific parameters */ struct cop_job_handle_s* next; /**< next job */ } cop_job_handle; The job dispatch process (see Figure 4.3) is outlined in the following steps: 1. User application handles the following: a. Prepares a job array (may be a single element). b. Calls osCopChannelDispatch(jobs)to send a channel to enqueue jobs. c. Passes the array and element(s) to osCopChannelDispatch(). 152 SmartDSP OS User Guide
  • 153. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) NOTE Use jobs from the memory pool; do not allocate stack jobs. A job pointer is returned after reaping. 2. COP layer handles the following: a. Queues all job pointers, taken from the application layer, into the confirmation job queue of the local memory. b. Uses lldChanelDispatch(jobs)to dispatch/add jobs to the MAPLE–B/B2 memory BD ring. c. Passes the array to the LLD at job completion. 3. LLD handles the following: a. Prepares BD(s). b. Initiates a callback function. copChannelDispatchCb(job,status)is used to send BD(s) from MAPLE-B/B2 to local memory. c. Copies the Job ID into the BD Task ID field. LLD job description tries to match the BD to allow for a simple sanity check and easy BD preparation. NOTE During release, sanity checks are not asserted in order to save runtime code. 4. COP calls a user-defined callback function; see Figure 4.3. SmartDSP OS User Guide 153
  • 154. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) Figure 4.3 MSBA8100 COP Job Description Procedure NOTE Data cache coherency is unsupported as neither COP nor LLD manage data. Consume (Reap) Flow Job reaping is performed under the following circumstances: • Triggered interrupt is enabled. • Interrupt is disabled following job dispatch. • Channel control function is called during runtime. Job reaping process covers the following: • LLD iterates over a BD ring. 154 SmartDSP OS User Guide
  • 155. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) • LLD calls the COP callback function with the BD status—for each BD. • COP dequeues a job pointer and calls a user callback function. Before dispatching the job, the user application should have data ready in the MAPLE–B/B2 accessible memory: – MSBA8100: M2, DDR – MSC815x : M2, M3, DDR0, DDR1 Programming Model This section covers driver bring-up—first by the OS, then by the application-chosen API. General The MAPLE driver is part of the COP abstraction layer; all driver functions are activated via COP-layer functions. Bring-up initialization is based on initialization structures defined in msc81xx_config.c. Table 4.28 Driver Functions Function Description osCopDeviceOpen() Opens a MAPLE or XxPE device. osCopChannelOpen() Opens a channel for an XxPE device. osCopChannelCtrl() Manipulates an XxPE channel. osCopDeviceCtrl() Manipulates an XxPE device. osCopChannelDispatch() Dispatches a job list to a channel. osInitialize() SmartDSP OS initialization using structures defined in msc81xx_config.c SmartDSP OS User Guide 155
  • 156. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) Calling Sequence Example Table 4.29 MAPLE–B/B2 Driver API Table 4.30 Status Name Description Kernel Bring-up osInitialize()-> • User application osArchDevicesInitialize()-> indirectly calls these functions. mapleInitialize()-> • osInitialize() copRegister() calls mapleInitiali ze()based on os_config.h defines and msc81xx_confi g.c configuration structures. • Initializes MAPLE driver. • copRegister() takes and registers the driver in the COP LLD layer. osInitialize()-> • mapleXxpeInitia osArchDevicesInitialize()-> lize() initializes MAPLE XXPE. mapleXxpeInitialize()-> • mapleXxpeInitia copRegister() lize()calls copRegister() . 156 SmartDSP OS User Guide
  • 157. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) Table 4.30 Status Name Description Application Bring- osCopDeviceOpen()-> • Using given up mapleOpen()-> parameters, osCopDeviceOp maple_init() en() opens a COP device for operation; it returns a device handle or NULL. • mapleOpen()open s a MAPLE–B/B2 channel and returns channel handle. • maple_init()ini tializes the MAPLE–B/B2 controller. osCopDeviceOpen()-> • Using given mapleXxpeOpen() parameters, osCopDeviceOp en() opens a COP device for operation; it returns a device handle or NULL. • mapleXxpeOpen() opens all supported PEs. osCopChannelOpen()-> • Using given mapleXxpeChannelOpen() parameters, osCopDeviceOp en() opens a COP device for operation; it returns a device handle or NULL. • mapleXxpeChanne lOpen()opens a MAPLE PE channel. SmartDSP OS User Guide 157
  • 158. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) Table 4.30 Status Name Description Application osCopChannelDispatch()-> • osCopChannelDis Runtime mapleXxpeChannelDispatch() patch() sends a job to a channel previously opened for transmission. • mapleXxpeChanne lDispatch() sends a message. osCopDeviceCtrl()-> • osCopDeviceCtrl mapleDeviceCtrl() ()performs control commands on a device. • mapleDeviceCtrl () performs a device-level controlling function. osCopChannelCtrl()-> • osCopChannelCtr mapleXxpeChannelCtrl() l()performs control commands on a channel. • mapleXxpeChann elCtrl()perfo rms a channel control-level function. mapleXxpeIsr()-> • Invokes an mapleXxpeChannelReap()-> interrupt service copChannelDispatchCb() routine when the PE triggers an interrupt. • While polling a channel for finished jobs, the reap process can be activated indirectly using osCopChannelC trl(). Functionality The following section covers HW semaphores, initialization processes and runtime. 158 SmartDSP OS User Guide
  • 159. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) HW Semaphores MAPLE HW configuration allows for HW semaphores if they are located on the MAPLE- instantiated device. • Semaphores synchronize usage when several entities, including MAPLE, generate sRIO doorbells in the system. Applicable for MSC815x, but not MSBA8100. • Synchronize access to shared resources when devices share the same MAPLE; see MAPLE Resource Sharing. NOTE SmartDSP OS doorbell driver does not support HW semaphores. Configuration File SmartDSP OS configuration file, os_config.h, enables MAPLE-B/B2 and PE by setting the below noted MAPLE and MAPLE_XXPE flags to ON. For example, • #define MAPLE ON • #define MAPLE_TVPE ON • #define MAPLE_FFTPE ON • #define MAPLE_DFTPE ON • #define MAPLE_CRCPE ON NOTE MSBA8100 does not support #define MAPLE_CRCPE ON. Initialization Processes Table 4.31 outlines the three initialization processes. Table 4.31 MAPLE–B/B2 Initialization Processes Process Description Driver Initialization • Initializes MAPLE-B/B2. • Enables a PE-specific driver at compilation time. SmartDSP OS User Guide 159
  • 160. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) Table 4.31 MAPLE–B/B2 Initialization Processes Process Description PE Initialization • Specifically LLD (MAPLE and all XxPE). • Opens the device via the COP interface. • Returns a device handle. Channel Initialization • Opens a MAPLE-B/B2 channel via the COP interface. – Achieved using the device handle returned by PE initialization. • Returns a channel handle. • One-to-one relationship exists between a channel and a BD ring. – Every MAPLE-B/B2 PE supports up to eight high- and low-priority channels. • COP channels are not statically assigned to cores. – Cores open channels by specifying a required channel number. – Every core opens at least one channel to dispatch jobs. – A channel, opened by a given core, cannot be opened by another core. Table 4.32 details driver, PE, and channel initializations. Bring-up initialization is based on the initialization structures defined in msc81xx_config.c. 160 SmartDSP OS User Guide
  • 161. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) Table 4.32 MAPLE Initialization Processes Driver Initialization PE Initialization Channel Initialization 1. Initialize using functions 1. Initialize MAPLE–B/B2. 1. User application osInitialize() or calls runtime 2. Call osCopChannelOp osCopDeviceOpen(). osCopDeviceOpen() en(). to open a COP – Configures MAPLE–B/ B2, DSP, and device. 2. User application is (optionally) MMU. provided with 3. Initialize PE. specific information: – Uploads µcode image based on a selected – channel number standard: 3GLTE, 4. User application 3GPP, 3GPP2, WiMAX, provides – channel priority or 3GPP2HS. MAPLE–B/B2 – interrupt line (if – Divided into specific instantiation (to which applicable) initializations: the PE belongs). – number of BDs SmartDSP OS or in the ring MAPLE–B/B2. 5. User application 3. Initialize COP and 2. Access MAPLE–B/B2 with provides PE LLD channels. MAPLE_IN_PLATFORM configuration: – COP channel value – MAPLE–B/B2 master initialization smartdsp_os_device.h configures PE. structure – Set to OFF: To access – First core to call contains a MAPLE, user provides function pointer to the osCopDeviceOpen LLD channel callback functions with a 32-bit access resolution. () configures the PE. initialization – MAPLE–B/B2 driver structure. – Set to ON: User provides device-to- provides callback 4. LLD uses MAPLE– functions; if none are core synchronization mechanisms. B/B2 DRAM to provided then driver synchronize the reverts to internal functions. following: memory, – If the driver is unfamiliar interrupts, and BD with the interface used ring assignments of to access MAPLE–B/B2, multiple devices then user application sharing MAPLE–B/ must provide a callback function to control R/W B2. access. – Multiple – If the driver does not channels—on perform data access, the same core— then user application can share the does not need to same MAPLE– provide a callback B/B2 interrupt function. line. SmartDSP OS User Guide 161
  • 162. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) Listing 4.4 is a code snippet used to access MAPLE–B/B2 memory space in a platform- independent manner. Listing 4.4 Function for Accessing MAPLE-B/B2 Memory Space typedef long (*maple_config_func)( void *addr, void *data, unsigned long int num_bytes, unsigned long int dev_id, unsigned long int param ); /**< MUST provide big-endian accesses towards MAPLE */ MAPLE-B/B2 Runtime The MAPLE–B/B2 driver does not handle data processed by the MAPLE-B/B2. User applications must ensure that all required data is in place before dispatching a job(s) using the MAPLE–B/B2 driver. The COP job list consists of a NULL-terminated, linked, structure list. Each structure points to the LLD job description. The following functions detail MAPLE–B/B2 driver runtime: 1. Dispatch a job to a channel and send BD(s) to the PE channel using osCopChannelDispatch(). 2. Returns OS_SUCCESS or an error code from os_error.h. The function takes the following arguments: – Channel handle as returned from osCopChannelOpen(). – Pointer to a job array. – Number of jobs for dispatch. 3. osCopDeviceCtrl()controls COP devices using the following commands: • MAPLE_CMD_SEMAPHORE_GET – Retrieves semaphore used for sharing the MAPLE-B/B2 driver. • MAPLE_CMD_SEMAPHORE_RELEASE – Releases semaphore used for sharing the MAPLE-B/B2 driver. • MAPLE_CMD_MALLOC – Allocates memory from the MAPLE-B/B2 DRAM. • MAPLE_TVPE_CMD_SET_VITERBI_POLY – Sets viterbi polynomial sets (MTVPVSxCyP). 162 SmartDSP OS User Guide
  • 163. Drivers Multi Accelerator Platform Engine–Baseband (MAPLE–B/B2) – Set BD VIT_SET field. – Select between sets using enumeration, maple_tvpe_vit_set_t. • MAPLE_TVPE_CMD_LOAD_INTERLEAVER – Used for 3GPP2HS EVDO. – Sets (MP_MBUS + 0x464) = &maple_tvpe_interleaver[0]. – Execute after the maple_init function but before BD activation. NOTE EVDO is not supported on all MAPLE platforms. See the Core Reference Manual for further information. 4. osCopChannelCtrl()controls COP channels using the following commands. • MAPLE_FTPE_CMD_RX_POLL – Polls xFTPE channel and BD ring for completed jobs. • MAPLE_TVPE_CMD_RX_POLL – Polls TVPE channel and BD ring for completed jobs. • MAPLE_CRCPE_CMD_RX_POLL – Polls CRCPE channel and BD ring for completed jobs. • No MAPLE-B/B2 channel commands. Source Code The MAPLE SmartDSP OS driver can be used as is with inclusion of the Driver Initialization and Runtime header files. The other files—µcode Initialization API, µcode header file, and MAPLE Driver memory map—are included in the driver initialization and runtime files. Table 4.33 Source Codes Source Type Detail Library Driver “SmartDSPlibmsc815x*_drive rs.elb” Kernel “SmartDSPlibmsc815x*.elb” MAPLE µcode "SmartDSPlibmaple*.elb" SmartDSP OS User Guide 163
  • 164. Drivers RIONET Table 4.33 Source Codes Source Type Detail Files Driver Initialization Header File "SmartDSPinitializationarchpe ripheralsmapleinclude*.h" Driver Runtime Header File “SmartDSPdriversmaplerev1i nclude*.h” µcode Initialization API "SmartDSPinitializationarchpe ripheralsmaplemaple_apimsc 81XXincludemaple_api.h" µcode Header File "SmartDSPinitializationarchpe ripheralsmaplemaple_apimsc 81XXrevXinclude*" MAPLE Driver Memory Map “SmartDSPincludearchperiph eralsmaplerevX*” Demo Use Cases MAPLE–B/B2 driver demos: “SmartDSPdemosstarcoremsc815xmaple_*” “SmartDSPdemosstarcoremsc815xmapleb2_*” “SmartDSPdemosstarcoremsc814xmaple_*” RIONET RIONET supports messaging between source and destination and allows the tunneling of TCP/IP over RapidIO. Features RIONET features are noted below: • BIO-based and, as such, can plug into the network stack. • Allows the tunneling of TCP/IP over RapidIO. • Uses interrupt/polling to process frames received from QE. • RIONET QE μ code is only used for Rx. • RIONET LLD: 164 SmartDSP OS User Guide
  • 165. Drivers RIONET – On Tx, adds LLD-specific header to a message. – QE uses added information to route messages to the proper BIO channel on Rx. – Manages queues and spinlocking for Tx. Relevant SoC Relevant SoCs are those that include the RMU (i.e., MSC814x and MSC8156 and their derivatives). Architecture This section covers the SW architecture of the RIONET driver. Driver Components This section details RIONET driver components. See Table 4.27 for further details. Table 4.34 RIONET Driver Components Table 4.35 Components Description BIO Abstraction Layer • BIO module layer. • See Chapter 2, BIO Module. Channel • For Rx: de-multiplexed messages from mailbox based on RIONET headers. • For Tx: QE transmission queue. Device • Abstraction to an RMU mailbox. • Loads μ code during opening. OS Frame • Message to send. OS Frame Buffer • Message data to send. RIONET LLD • Functions are activated via BIO abstraction layer functions. Figure 4.4 shows how RIONET manages queues and handles interrupts. SmartDSP OS User Guide 165
  • 166. Drivers RIONET Figure 4.4 RIONET Usage for Queue Management and Interrupt Handling Data Flow RIONET uses a message-passing programming model for inter-processor and inter-device communication. The model allows messages to be sent across the interconnect fabric to the message HW of a consumer mailbox. Transmit Flow There is one transmit queue per mailbox and no μ code support. Each SoC core obtains (and releases) the Tx spinlock and transmits via that single queue. User application follows these steps for a BIO Tx call: 1. Enqueues a frame on the frame queue. 2. Obtains a spinlock in order to take control of the shared Tx queue. 3. Places frame buffer(s) on the LLD BD(s). 4. Triggers the LLD transmission. 5. Frees the spinlock. 6. Receives a number of previously transmitted BDs (if no LLD Tx interrupts) and handles them as follows: a. Dequeues the frame from the frame queue. b. Calls the OS BIO Tx callback function with the frame. 166 SmartDSP OS User Guide
  • 167. Drivers RIONET NOTE RIONET Tx has LLD MMU and cache support. Receive Flow RIONET supports interrupt and/or Rx polling indications. • MSC814x DSP uses virtual interrupts only. • MSC815x DSP uses virtual interrupts and direct interrupt lines (from QE to core). There are n (application configurable) number of separate Rx queues for a mailbox. • Each core opens its Rx channel(s); all must be open before RIONET is enabled. • Each Rx channel has the following: – A unique identifier (comprising the RIONET application or LLD header) for receiving frames. – One Rx queue that accepts frames sent to the designated identifier. • QE µcode copies incoming data to prevent overwriting on the HW cyclic buffers. Rx flow steps: 1. For an open LLD channel, the user application takes these steps for each Rx BD in the BD ring: a. Takes the buffer from the BIO buffer pool. b. Enqueues the buffer on the BIO buffer queue. c. Places the buffer on the LLD BD. 2. Upon execution of LLD Rx ISR—by polling or interrupt—the user application handles ready BDs (in the BD ring) as follows: – Replaces a current buffer (on LLD BD) with a new one from the buffer pool. – Prevents LLD underrun by reusing the current buffer (if another buffer is unavailable). – Looks for buffer errors; if found in the LLD BD then the HW registers the buffer in the BD and logs it in BIO. 3. If there are no errors, the user application follows these steps: a. Dequeues the buffer from the BIO buffer queue. b. Takes a frame (equivalent to buffer handle) from the BIO frame pool. c. Constructs a frame from the buffer. d. Calls the BIO Rx callback function. SmartDSP OS User Guide 167
  • 168. Drivers RIONET NOTE RIONET Rx has LLD MMU and cache support. For frame/frame pool information, see Hardware Abstraction Layers (HAL). Programming Model This section covers driver bring-up—first by the OS, then by the application-chosen API. General MSC814x and MSC815x RMUs each have 2 mailboxes; however, they do not store message header information in their memory. During enqueueing, only the HW holds message information. This can lead to the following issues: • Introduces queue management problems—identifying which core will handle a message based on a letter ID. • Introduces interrupt management problems—interrupt handling. QE solves and prevents these problems as follows: • QE μ code package, included in RIONET, is triggered by sRIO controller interrupts that are wired by the SoC to the QE. • QE (not BIO channel cores) manages RIONET queues. • QE (not the sRIO controller) manages sRIO messaging queues. • Each mailbox has its own queue: – QE (not the HW) manages queues. – QE (not RIONET channel cores) manages queues. • QE interrupts the cores: – VIRQ and/or dedicated interrupt lines are used for incoming messages. – QE copies incoming messages—from the sRIO inbound queues mailbox—to each core destination. Calling Sequence Example Table 4.36 describes functions included in the architecture-independent API of the SmartDSP OS RIONET driver. Functions include kernel bring-up, application bring-up, application runtime, and application teardown. 168 SmartDSP OS User Guide
  • 169. Drivers RIONET Table 4.36 Architecture-Independent RIONET API Status Name Description Kernel Bring-up osInitialize() -> • User application osArchDevicesInitialize() - indirectly calls these > functions. qeInitialize() • osInitialize() calls osArchDevicesIni tialize() based on os_config.h defines and msc81xx_config.c configuration structures. • Initializes QE driver. osInitialize() -> • osArchDevicesInit osArchDevicesInitialize() - ialize() calls > rionetInitialize (); this initializes the rionetInitialize() -> RIONET driver. bioRegister() • In turn, bioRegister() is called: – Takes and registers the driver to the BIO abstraction layer. – Returns a pointer to the BIO device handle. – Successful registration results in a BIO device handle different than NULL. SmartDSP OS User Guide 169
  • 170. Drivers RIONET Table 4.36 Architecture-Independent RIONET API (continued) Status Name Description Application osBioDeviceOpen() -> • Must be first function Bring-up rionetOpen() called at this stage. • Returns a BIO device handle; handle is a parameter for calling other functions. • Calls rionetOpen() to open a mailbox. osBioChannelOpen() -> • Opens a pre- rionetChannelOpen() allocated BIO device channel. • Initializes channel structure as per configuration parameters. • Calls rionetChannelOpe n() to open the RIONET channel. 170 SmartDSP OS User Guide
  • 171. Drivers RIONET Table 4.36 Architecture-Independent RIONET API (continued) Status Name Description Application osBioChannelTx() -> • Via a BIO channel, Runtime rionetChannelTx() osBioChannelTx() transmits a frame previously opened for transmission. • Calls rionetChannelTx( ) to send a message to the BIO layer. osBioDeviceCtrl() -> • osBioDeviceCtrl() rionetCtrl() performs control commands on a device. • Calls rionetCtrl() to perform a device- level control function. osBioChannelCtrl() -> • osBioChannelCtrl( rionetChannelCtrl() ) performs control commands on a channel. • Calls rionetChannelCtr l() to perform a channel-level control function. rionetTxIsr() • Calls an interrupt service routine after a packet has been sent. • Packet configured to issue an interrupt. rionetRxIsr() • Calls an interrupt service routine after a packet has been received. • Packet configured to issue an interrupt. Functionality This section details RIONET initialization, runtime, and network stack interactions. Initialization Follow these steps to initialize RIONET. SmartDSP OS User Guide 171
  • 172. Drivers RIONET 1. RIONET initialization header file: initialization/arch/msc81xx/include/msc81xx_rionet_init 2. Enable RIONET mailboxes by defining the following in os_config.h: #define MSC81XX_RIONET0 ON #define MSC81XX_RIONET1 ON 3. Enable SRIO by defining the following in os_config.h: #define MSC815X_SRIO ON NOTE See “SmartDSP OS API Reference Manual” for a complete description of srio_init_params_t and rionet_init_params_t. 4. In “mcs81xx_config.c” file, set “srio_init_params_t srio_init_params” for SRIO ports initialization. For example, srio_init_params_t srio_init_params = { 2, { { SRIO_PORT0, SRIO_CONNECTIVITY_MODE, TRUE, NULL, NULL }, { SRIO_PORT1, SRIO_CONNECTIVITY_MODE, TRUE, NULL, NULL }, } }; 172 SmartDSP OS User Guide
  • 173. Drivers RIONET 5. In file “mcs81xx_config.c”, set “rionet_init_params_t rionet_init_params_(0/1)” for RIONET initialization. Set rionet_init_params_t.rionet_flags as follows: • Set RIONET_FIXED_SIZE_AND_QUEUE to use a fixed packet size—as used in rionet_init_params_t.frame_size and fixed queue (queue 0) for all incoming traffic. NOTE Use RIONET_FIXED_SIZE_AND_QUEUE mode only with drivers recompiled with CUSTOMER_SPECIFIC_RIONET definition. • Set RIONET_DONT_DROP_PACKETS to prohibit RIONET from dropping packets if the RIONET queue is full. For example, rionet_init_params_t rionet_init_params_0 = { 0, INBOUND_FRAME_SIZE_256, INBOUND_QUEUE_SIZE_2, (OS_NUM_OF_CORES * TEST_NUM_OF_CHANNELS), TEST_NUM_OF_TX_FRAMES, OUTBOUND_QUEUE_SIZE_0002, OUTBOUND_SERVICE_CONTROL_FIX, (int8_t)0xFF, 2 *TEST_NUM_OF_TX_FRAMES, 2 * TEST_NUM_OF_TX_FRAMES, OS_HWI_PRIORITY1, OS_HWI_PRIORITY1, Rionet0Buffer_b, Rionet0Buffer_b + RIONET_BUFFER_SIZE, APP_LLD_HEAP, 0 }; NOTE For correct driver functionality, take note of the following restrictions: — Set tx_queue_size (Tx frame queue size) to comply with BIO restrictions. SmartDSP OS User Guide 173
  • 174. Drivers RIONET — BIO Tx confirmation queue must be the same size (or larger) than the LLD Tx BD ring (tx_q_sz). Users must ensure (as per the traffic profile) that this restriction is always maintained. — In RIONET the Tx BD ring is shared; therefore, the LLD cannot assert on a misconfiguration. 6. Rx μ code is loaded during osInitialize(). As described above, the user needs to initialize the rionet_init_params_t. The μ code header also contains a HW-defined packet size and RIONET version. 7. Open a RIONET (0/1) device using osBioDeviceOpen(). 8. Create a frame pool using osFramePoolCreate(). 9. Create a buffer pool for the Rx channels. 10. Open Rx and/or Tx channels—for an open RIONET device—using osBioChannelOpen(). 11. Use osBioDeviceCtrl(RIONET_CMD_ENABLE)for the following: – To check that all channels/devices are open. – To enable QE and SRIO for mailboxes. Runtime Follow these steps during RIONET application runtime: 1. Use osFrameGet() for new frame allocations and osFrameBufferNew() for new data buffer allocations. 2. Initialize data buffer and frame information using osFrameAAAA()manipulation functions. 3. Provide packet information for routing in the RIONET application (or LLD) headers. 4. Use macros to set the correct RIONET application (or LLD) header field; see Table 4.37. Eight-byte RIONET header structures are shown in Figure 4.5. Table 4.37 RIONET Header Fields RIONET Header Field Description #define • Sets destination sRIO device ID. RIONET_SET_DST_ID(PACKET, DATA) #define • Sets a destination sRIO mailbox for a RIONET_SET_DST_MB(PACKET, packet. DATA) 174 SmartDSP OS User Guide
  • 175. Drivers RIONET Table 4.37 RIONET Header Fields RIONET Header Field Description #define • Sets a destination RIONET BIO RIONET_SET_DST_CH(PACKET, channel for a packet. DATA) • QE responsible for moving the received packet. #define • Sets the sRIO port that will transmit a RIONET_SET_PHY_PORT(PACKET, specified message. DATA) • Only applicable for MSC815x. Figure 4.5 RIONET Header Structure 5. Use osBioChannelTx() for frame transmission. 6. In a non-interrupt mode, use the following to poll an Rx channel, osBioChannelCtrl(RIONET_CMD_CHANNEL_RX_POLL). RIONET and Network Stack The RIONET driver and network stack can work together. Rx: SmartDSP OS User Guide 175
  • 176. Drivers RIONET • BIO Rx channel callback function is set to the network stack input point, etherInput(). • RIONET driver plugs into the network stack when calling etherInput(). Tx: • Transmissions are sent using net stack transmit functions; e.g., udpSend() and tcpSend(). Precautions 1. During initialization, users can choose if QE will drop packets on underrun or continue with them. Use RIONET_DONT_DROP_PACKETS in the rionet_flags field of the rionet_init_params_t structure. NOTE QE continuing with packets is default RIONET μ code behavior that can potentially cause sRIO retry errors. Overriding the default can, however, lead to sRIO controller congestion and retry errors. 2. When interfacing the network stack, the application must populate the ARP table ahead of time as RIONET receive functions cannot deal with ARP discovery packets. NOTE ARP is not supported in RIONET. Source Code RIONET driver header files and additional libraries: Table 4.38 Source Type Detail Library Driver “SmartDSPlibmsc81xx*_drive rs.elb” Kernel “SmartDSPlibmsc81xx*.elb” Board Support Package "SmartDSPdemosstarcorems c81xxads_supportads_project bsp_msc81xxads.elb" 176 SmartDSP OS User Guide
  • 177. Drivers Time Division Multiplexing (TDM) Table 4.38 Source Type Detail Files Driver Initialization “SmartDSPinitializationarchm sc815xincludemsc815x_rionet _init.h” Driver Runtime "SmartDSPincludearchstarcor emsc815xmsc815x_rionet.h" Resource Management Note the following Tx and Rx resource management issues: • Manage the Tx queue by spinlock. • Manage a Tx completion indication using a pre-allocated array (size of Tx queue) on heap; this is indicated in the initialization structure rionet_init_params_t. • Each Tx channel requires one each of the following: frame queue and frame pool. No buffer queues or pools are required. For more information see the BIO chapter. • Each Rx channel requires one each of the following: frame queue, frame pool, buffer queue, and buffer pool. Channel buffer pools and queues can be the same as those in the BIO device. For more information see the BIO chapter. Demo Use Cases RIONET driver demos: • “SmartDSPdemosstarcoremsc814xrionet” • “SmartDSPdemosstarcoremsc814xamc_ecli” • “SmartDSPdemosstarcoremsc815xrionet” Time Division Multiplexing (TDM) The SmartDSP TDM driver functions as an SIO device; it belongs to the SIO LLD layer (under the SIO layer) that manages data serialization and device registration. Features TDM is characterized as follows: • Implements transfer protocol and data management. SmartDSP OS User Guide 177
  • 178. Drivers Time Division Multiplexing (TDM) • Interface enables communication—among many devices—over a single bus. • Interface is composed of four identical but independent TDM modules. • Each module supports 256 channels; the channels run at a maximum of 50 Mbps and have a word size of 2, 4, 8, and 16-bits. • Manages traffic by allowing only one device to drive the bus for each channel. • When a channel is active, each device drives its active transmit channels and samples its active receive channels. • System designer must guarantee that there are no conflicts in transmit channel allocation. • Used with both linear and nonlinear encoding. Operates without any data copying to provide efficient Tx/Rx flow from user application to driver; this reduces the application’s required memory space. Relevant SoC Architecture TDM driver only supports a double-buffer paradigm; thus Tx and Rx buffers are divided into two parts. The first part is processed by the user application, the second part is transmitted or received. TDM implementation follows these steps: 1. TDM Initialization 2. Tx/Rx Process 3. Control Operation Data Flow TDM Tx/Rx Process All sent/received buffers are passed to the user application via the data callback. The data callback, a user application function, is supplied to the driver when a channel opens. An open channel can be connected as a data callback parameter even if working with the same callback for different channels. NOTE Users allocate the handle for the SIO channel and, when opening the channel, can specify it as a parameter. • User application, with a channel handle, can call osSioBufferGet() to get a new buffer. 178 SmartDSP OS User Guide
  • 179. Drivers Universal Asynchronous Receiver/Transmitter (UART) • User application, before a driver demand, must release the “new buffer” by calling osSioBufferPut(). If not, the application error callback function may be called. Programming Model TDM Initialization SmartDSP OS calls tdmInitialize() to initialize the TDM driver. The user application should not call this function directly. The TDM driver is initialized if the configuration file MSC81xx_TDM0 flag is set to ON. Function tdmInitialize() characteristics include the following: • Takes the TDM module index (0, 1, or 2) as a parameter. • Configures TDM registers according to configuration parameters of the initialization structure. • Sets application-specific routines for the TDM interrupt handlers. • Registers the TDM driver to the SIO layer; consequently, user application can use the TDM device via the SIO API. Use osSioDeviceOpen()to open the TDM device during the user application initialization phase. During Tx and Rx operations, the user application opens/closes needed Tx/Rx channels using osSioChannelOpen()/ osSioChannelClose(). TDM Control Operation SIO API supplies both device and channel control functions to handle all common SIO commands; e.g., tdmCtrl() and tdmChannelCtrl(). Demo Use Cases Universal Asynchronous Receiver/ Transmitter (UART) Introduction A universal asynchronous receiver/transmitter, abbreviated UART , is a type of "asynchronous receiver/transmitter", a piece of computer hardware that translates data between parallel and serial forms. The universal designation indicates that the data format SmartDSP OS User Guide 179
  • 180. Drivers Universal Asynchronous Receiver/Transmitter (UART) and transmission speeds are configurable and that the actual electric signaling levels and methods (such as differential signaling etc) typically are handled by a special driver circuit external to the UART. Features SmartDSP OS UART driver provides a full-duplex port for serial communication with other devices. UART, or SCI, features the following: • Implemented as a CIO driver that provides channelized abstraction with other peripherals. • Uses two dedicated signals to transmit (UTXD) and receive (URXD) data. • [Optional] Generates, during reception, an interrupt request when a new character is available to the UART data register (SCIDR). The core then reads the character from the data register. [Optional] Generates, during transmission, an interrupt request when its data register can be written with new characters. The core then writes the character to the data register. Architecture UART Implementation UART implementation includes the following steps: 1. UART Initialization 2. Transmit Process 3. Receive Process Control Operation Data Flow Transmit/Dispatch Flow The UART Tx process follows these steps: 1. User application starts the transmit process by calling osCioChannelTx(). 2. CIO driver calls uartChannelTx()with the data pointer and size. 3. UART driver enables the device for transmission and stores the data pointer and size. The driver does not yet copy any characters to the data register. 180 SmartDSP OS User Guide
  • 181. Drivers Universal Asynchronous Receiver/Transmitter (UART) 4. UART generates a TDRE every time a new character is available in the data register. 5. uartGeneralIsr(), which handles the interrupt, calls uartTransmitIsr() to handle the TDRE event. 6. The driver, during uartTransmitIsr(), performs the following: • writes a single character to the data register; and, • notifies CIO that a character was transmitted. Driver disables TDRE (until uartChannelTx() is called again) if no characters remain for transmission. Receive/Consume Flow The UART Rx process follows these steps: 1. User application starts the receive process by calling osCioDeviceCtrl() 2. UART driver enables the device for reception by creating and enabling a channel osCioChannelCtrl() 3. UART generates an RDRF every time a new character is available in the data register. 4. uartGeneralIsr(), which handles the interrupt, calls uartReceiveIsr() to handle the RDRF event. 5. The driver, during uartReceiveIsr(), performs the following: • requests a free buffer from CIO; • reads the character from the data register into the free buffer; and, • notifies CIO that a character was received. 6. If address wakeup mode was configured at initialization, uartReceiveIsr() checks a received character before passing it to CIO—to verify that it is an address character. NOTE Address characters are not passed to CIO. Programming Model UART Initialization SmartDSP OS calls uartInitialize()to initialize and configure UART registers according to configuration parameters in the initialization structure. • UART driver is initialized if the configuration file (os_config.h) flag MSC81xx_UART_ON flag is set to ON. SmartDSP OS User Guide 181
  • 182. Drivers Universal Asynchronous Receiver/Transmitter (UART) • UART driver initialization header file (msc81xx_uart_init.h) contains the UART driver initialization structure definition. • User application can create a structure instance, set desired values, and pass them to the uartInitialize() function. • User application can pass NULL to uartInitialize()and use the default UART parameters shown in Listing 4.5. • User application can override this configuration by setting desired values in the initialization structure. • uartInitialize()also registers the UART driver in the CIO layer: – Allows user application to use the UART device via the CIO API. – Enables UART device for Tx and Rx operations. Listing 4.5 Default UART Parameters typedef struct { uint8 wiring_mode = UART_MODE_NORMAL; uint32 baud_rate = 57600; uint8 parity = UART_PARITY_ON; uint8 parity_type = UART_PARITY_EVEN; uint8 tcie = UART_TCIE_OFF; uint8 data_format = UART_DATA_FORMAT_9BITS; uint8 wakeup = UART_WAKE_IDLE_LINE; uint8 idle_line_type = UART_ILT_AFTER_START_BIT; uint8 rx_addr = 0; } msc81xx_uart_init_params_t; UART Control Operation uartCtrl() function handles control commands that enable/disable transmission, reception, and other UART interrupts. Demo Use Cases demosstarcoremsc814xuart demosstarcoremsc815xuart 182 SmartDSP OS User Guide
  • 183. 5 Network Stack This chapter explains the SmartDSP OS Network (Net) Stack module. The Net Stack module can be used by an application to communicate with other applications or devices. This chapter consists of the following topics: • Net Stack in SmartDSP OS • Supported Protocols Net Stack in SmartDSP OS This topic explains the conceptual model, initialization, and compile-time configuration of Net Stack module in the SmartDSP OS. This topic consists of the following sub-topics: • Conceptual Model • Initialization • Compile-time Configuration Conceptual Model The Net Stack module is a software stack that supports frame based protocols, see Figure 5.1. In addition, the module: • acts in conjunction with the Buffer I/O module of SmartDSP OS • lets you write user-defined callback functions • supports MSC814x (MSC814x ADS) and MSC815x (MSC815x ADS) platforms The current implementations are: • Ethernet • RapidIO® (with SmartDSP OS RIONET headers) Figure 5.1 SmartDSP OS Net Stack Module SmartDSP OS User Guide 183
  • 184. Network Stack Net Stack in SmartDSP OS The IP layer is the primary protocol in the Net Stack module and almost all the modules call it internally. Typically, user do not use the IP module directly. Instead, the protocols running on top of the IP layer are utilized. However, there are user level API functions that user can call in order to work directly with IP stack (inSetIPCallBack() and ipOutput()). The Net Stack module supports both single and multi buffered frames. It is up to the user to choose the appropriate Net stack library suitable for the application. Single buffered frames supporting targets are compiled with FRAME_SINGLE_BUFFER_ONLY flag. Figure 5.2 shows the conceptual model of Net Stack module in SmartDSP OS. 184 SmartDSP OS User Guide
  • 185. Network Stack Net Stack in SmartDSP OS Figure 5.2 Conceptual Model of Net Stack in SmartDSP OS Application Program SmartDSP OS Direct Socket API Callback Functions TCP/IP Stack ICMP Module TCP Module UDP Module DHCP Module SRTP Module ICMP Output TCP Input UDP Input DHCP Input SRTP Input IPSec Module IP Module IP Output IP Input Interface Module (Ethernet) Ethernet Output ARP Ethernet Input COP BIO Serializer osBioChannelTx Serializer Callback BIO Low Level Driver LLD Function SmartDSP OS User Guide 185
  • 186. Network Stack Net Stack in SmartDSP OS Initialization NOTE User should use lib/net_debug_xxx.lib for single buffered frames debug version and lib/net_lib_xxx.lib for release version. For multi- buffered frames support lib/net_multi_debug_xxx.lib and lib/ net_multi_lib_xxx.lib should be used. Following functions are called during initialization of net stack in SmartDSP OS: • ifCreate() — Called by the OS to open BIO channels, and call the interface specific type initialization function. • tcpInit() — Called by the OS to initialize IP TCP socket descriptors, TCP descriptors table, and mark all sockets as unused. • udpInit() — Called by the OS to initialize IP User datagram protocol (UDP) socket descriptors. • udpSocket() — Called by the user application to retrieve IP UDP socket descriptor. • inSetAddr() — Called by the user application to set the local address. It sets all network parameters according to the address and sends ARP request. • inSetDefGateway() — Called by the user application to set default gateway's address for interface. • dhcpStart() — Called by the user application to start the DHCP client. For ifCreate(), create a memory partition, a frame pool, the transmit and receive BIO channels, and specify a MAC address and protocol type (IFT_ETHER and IFT_ETHER_VLAN is currently supported). Also initialize all the BIO channels. The Net Stack module is hardware independent. It uses the memory partition manager and frame pool handlers to create frames (primarily the ICMP and DHCP sub-modules) and delete frames after a transmit operation completes. The Net Stack module supports Virtual LAN (VLAN) 802.1Q. To enable it, you can call the ifCreate() function with a parameter, IFT_ETHER_VLAN. The created VLAN interface must be attached to the physical interface that was previously created. After attaching the interface, the IP network address and VLAN tags should be defined using the source code. Refer to SmartDSP OS API Reference Manual for more information. After initializing the VLAN interface, the network stack multiplexes all frames arriving towards the physical interface, using the VLAN tag of the frame. 186 SmartDSP OS User Guide
  • 187. Network Stack Net Stack in SmartDSP OS Compile-time Configuration You can configure the compile options of the Net Stack module using the net_config_.h file. The description of the compilation flags in the net_config_.h file is as follows: • ON indicates that the feature will be included in the code and OFF indicates that the feature will not be included in the code. • IF options – IF_VALIDATE_LENGTH — Length validation at IF level including Maximum Transmission Unit (MTU) verification. – IF_STATISTICS — Statistics gathering for interface layer. – INET6 — Ipv6 support (currently not implemented). • IP options – IP_VALIDATE_LENGTH — Packet length (except MTU), header length, and version validation at IP layer. – IP_CHECK_ADDRESS_VALIDITY — IP address validation. – IPOPTIONS — IP options handling. – INET — Ipv4 support (should always be ON). – IP_CHECK_CHECKSUM — Checksum validation of incoming packets (should be ON according to RFC1122). • UDP options – UDPCHECKSUM — Checksum computing and validation for UDP. – UDP_ERROR_CHECKING — Validation of parameters. – UDP_STATISTICS — Statistics gathering for UDP layer. • RTP options – RTP_EXTENSION_HEADER_SUPPORT — Support for RTP header extension. • DHCP options – DHCP_EVENTS_PRINT — Logging or printing of all the DHCP events. – DHCP_DOES_ARP_CHECK — Support for checking the validity of IP address. NOTE You must recompile the network stack module after modifying the net_config_.h file. Table 5.1 shows the status of compilation flags in the net_debug.lib and net.lib library files. SmartDSP OS User Guide 187
  • 188. Network Stack Supported Protocols Table 5.1 Compilation Flag Status in net_debug.lib and net.lib Files Compilation Flags net_debug.lib net.lib IF_VALIDATE_LENGTH ON OFF IF_STATISTICS ON OFF IP_VALIDATE_LENGTH ON OFF IP_CHECK_ADDRESS_VA ON OFF LIDITY INET ON OFF IP_CHECK_CHECKSUM ON ON UDP_ERROR_CHECKING ON OFF UDP_STATISTICS ON OFF DHCP_SUPPORT ON ON DHCP_EVENTS_PRINT OFF OFF Supported Protocols Net Stack module supports the following protocols: • IPv6 Network • Dynamic Host Control Protocol (DHCP) • Real-time Transport Protocol (RTP) or Secure Real-time Transport Protocol (SRTP) • Real-time Transport Control Protocol (RTCP) • Uniform Data Packet (UDP) • Transmission Control Protocol (TCP) • Internet Control Message Protocol (ICMP) • Internet Protocol (IP) • IP Security (IPSec) • Address Resolution Protocol (ARP) • Management Information Base (MIB) 188 SmartDSP OS User Guide
  • 189. Network Stack IPv6 Network IPv6 Network Net stacks enable applications to communicate with both applications and devices. OSI model is the basis for SmartDSP OS net stack implementation; it allows the net to be divided into five or seven layers. Each layer, which is composed of several protocols, has a specific and independent function. The stack implements the second to fourth layers. The IP protocol is implemented in the third (Internet) layer. The net stack supports two versions of this protocol: • IPv4, the first major version and still the most commonly used. • IPv6, the newest (next generation) version. Each version features a set of protocols that assist functionality; for example, Neighbor Discovery (ND) and ICMPv6 protocols assist IPv6. Features SmartDSP OS net stack features are listed below: • Supports UDP protocol over IPv6. • Utilizes ND: – Performs discovery of other nodes on the link. – Determines node Link Layer addresses. • Supports a pinging utility over IPv6 using ICMPv6 echo request and reply. • IPv6 stack can run a multi-core environment. Currently, the net stack module supports only single buffer frames. Users must compile targets using the flag, FRAME_SINGLE_BUFFER_ONLY. Architecture Components The IPv4 net stack was the basis for the IPv6 net stack; both stacks share the second (Link) layer. The third and fourth layers are duplicated; each stack has its own protocols and functions. SmartDSP OS User Guide 189
  • 190. Network Stack IPv6 Network Design Decisions Compilation IPv6 net stack is an extension of IPv4. Features include the following: • Users can choose both or just one of these protocols. • Protocol selection is taken at compilation time; the linker removes unnecessary code if only a single protocol is used. • A single channel can support both protocols. • The correct interface is chosen based on the protocol of the received packets. Initialization The common IPv6 and IPv4 interface has pointers to specific protocol interfaces (ifnet4 and ifnet6). However, differences do exist between IPv6 and IPv4. • IPv6 has a different network interface, ifnet6. • ifnet6 includes fields relevant to both protocols; e.g., bio_chn_rx. • ifnet_general was defined to support both (and future) protocols on the same channel. Further, it maintains backward compatibility. Constraint IPv6 address constraints exist due to UEC hardware implementation. Users must assign IPv6 addresses whose final 24-bits are different for each channel. Data Flow Transmit Flow The transmit flow, which is invisible to the user. begins from the upper layer of the stack. The data is encapsulated with protocol headers while going down the stack: • Application sends data to the UDP layer, the IP layer, and finally to the Ethernet layer. • Performs MAC address resolution. • Initiates address resolution (if unregistered in the ND Table). • Sends an ND packet (while the old frame is pending resolution). • Transmits packet after address resolution. 190 SmartDSP OS User Guide
  • 191. Network Stack IPv6 Network Figure 5.3 Transmit Flow ICMP6 Output TCP/UDP Output Send ND IP6 Output Ethernet Output Unresolved Multicast/Unicast MAC Address ND Address Resolution Resolved Receive Flow According to the OSI model, every packet contains data encapsulated with headers. • Performs header parsing process upon packet receipt. • Each layer verifies and validates its packet header. • Passes valid packets to the next layer. SmartDSP OS User Guide 191
  • 192. Network Stack IPv6 Network Figure 5.4 Receive Flow Ethernet Input Ip6 Input ND ND Echo Echo TCP/UDP Input Received Neighbor Received Neighbor Reply Request Solicitation Advertisement ICMP6 Output ICMP6 Output ND Table Send Echo Reply Send Neighbor Advertisement (For packets waiting to be sent.) TCP/UDP Output Programming Model General During net stack compilation, set the below noted configurations in net_config.h. During the initialization stage, call the functions noted in the table. 192 SmartDSP OS User Guide
  • 193. Network Stack IPv6 Network Table 5.2 DMA Components Flow Stage Function Description Compilation: net_config.h INET6 • Set to ON for IPv6 enablement. IP6_VALIDATE_PACKET • IP layer header validation. ND_VALIDATE • ND header validation. Initialization ifGeneralCreate() • Initializes the general interface. if4Create() • Initializes IPv4 interface. • Binds it with the general interface. If6Create() • Initializes IPv6 interface. • Binds it with the general interface. In6SetAddr() • Called by the user application to set the local IPv6 address. • Sets all network parameters as per the address. udp6Init() • Initializes IPv6 UDP socket descriptors. udp6socket() • User calls function to get IPv6 UDP socket descriptor SmartDSP OS User Guide 193
  • 194. Network Stack IPv6 Network Example Calling Sequence Figure 5.5 Example Calling Sequence udp6Init() ifGeneralCreate() udp6Socket() If6Create() In6SetAddr() Demo Use SmartDSP OS provides several demo use cases that demonstrate net stack usage. For example, see the net_ip4_ip6_demo—in the msc815x demo directory—for IPv4 and IPv6 same channel support. The demos are SmartDSP-specific. Appendix Reference • SmartDSP OS API Reference Manual Dynamic Host Control Protocol (DHCP) The Dynamic Host Configuration Protocol (DHCP) is a network application protocol used by DHCP clients to obtain configuration information for operation in an Internet Protocol network. This topic consists of the following sub-topics: • DHCP Implementation • DHCP Initialization 194 SmartDSP OS User Guide
  • 195. Network Stack IPv6 Network DHCP Implementation The DHCP protocol allows a host to be configured dynamically. The DHCP client implementation is based on RFC 2131, but does not directly implement all the features of the protocol. Also, the implementation does not handle all DHCP options (RFC 2132). The DHCP Client supports the following options: • Option 1 – subnet mask • Option 3 – router address • Option 51 – address lease time • Option 53 – DHCP message type • Option 58 – address renewal time • Option 59 – address rebinding time The DHCP Client should be able to boot both from DHCP and BOOTP servers (RFC1534). Figure 5.6 shows the operation of DHCP. Figure 5.6 DHCP Operation SmartDSP OS User Guide 195
  • 196. Network Stack IPv6 Network DHCP Initialization To initialize the DHCP client: 1. Call the dhcpStart() or dhcpInform() function, as shown below: dhcpStart((struct ifnet*)&ifn, DHCP_DEFAULT_COARSE_TIMER_SECS, DHCP_DEFAULT_FINE_TIMER_MSECS); 2. The dhcpStart() function opens a UDP socket to broadcast a BOOTP/DHCP request. 3. An application may poll status of the DHCP client using the dhcpGetState() function, as shown below: dhcpStart(ifnet, DHCP_DEFAULT_COARSE_TIMER_SECS, DHCP_DEFAULT_FINE_TIMER_MSECS, FALSE); while( dhcpGetState(ifnet) != DHCP_BOUND) ) DHCP_BOUND means that the DHCP client was configured. NOTE The dhcpInform() function informs the DHCP server about pre-configured IP address. 4. To handle timeouts and lease time renewal, you can call the following functions: – dhcpFineTmr() — handles network timeouts, packet loss, and server delays. This function is called each DHCP_FINE_TIMER_MSECS seconds. – dhcpCoarseTmr() — enables lease renewal and rebind timeouts. This function is called each DHCP_COARSE_TIMER_MSECS seconds. You must call this function to allow DHCP client to perform the renewal or rebind activity. Because the UPD input goes through the inSetUdpCallBack() function (which sets the callback for UDP input packets), you can call the dhcpReceive() function everytime a packet arrives on DHCP_CLIENT_PORT on the ifnet port. This function is used to deliver all the packets to the DHCP client. Real-time Transport Protocol (RTP) or Secure Real-time Transport Protocol (SRTP) The RTP provides end-to-end transmission of real-time (audio and visual) data between computers. The SRTP provides security-related features, such as encryption, authentication, and integrity to the RTP data. This topic consists of the following sub-topics: 196 SmartDSP OS User Guide
  • 197. Network Stack IPv6 Network • RTP Implementation • RTP Initialization RTP Implementation Compared to the other protocols implemented by the Net Stack module, RTP has a different implementation. This difference stems from RTP's different role in the stack. RTP is intended to be malleable to provide the information required by a particular application and will often be integrated into the application processing rather than being implemented as a separate layer. The RTP's implementation is a collection of service routines that help the application build an RTP header and analyze the received RTP frames. Using these functions cannot impose any constraints on the application side because it is the application's responsibility to define the proper use of RTP. The RTP implementation does not use SmartDSP OS services in any way. RTP Initialization To initialize RTP: 1. You can call the rtpCreateContext() function to create a RTP context (that handles transmission of all RTP frames) for all outgoing connections, and rtpBuildHeader() to build the RTP headers for an RTP context, see Listing 5.1. Listing 5.1 Creating a RTP context and building a RTP header /* Create RTP context with */ /* sequence number 1234 */ /* ssrc 5678 */ /* initial time stamp 5665 */ /* payload type RTP_PCMU_PT */ rtpCreateContext(&rtp_context, 1234, 5678, 5665, RTP_PCMU_PT); /*Build a header for this context. (10 is a number that timestamp will grow) */ rtpBuildHeader(&rtp_context, 10, buffer); 2. You can change an RTP context at run-time using one of the rtpContextxxx() functions, such as rtpContextExtensionSet() and rtpContextSeqNumberSet(). 3. You can change fields in the RTP header using any of the rtpHeaderxxx functions, such as rtpHeaderPayloadLengthGet() and rtpHeaderPayloadTypeGet(). SmartDSP OS User Guide 197
  • 198. Network Stack IPv6 Network 4. For received frames, call the rtpPacketValidate() function to get field values. Real-time Transport Control Protocol (RTCP) The RTP is used in conjunction with the RTCP, which handles transmission of control information and Quality of Service (QoS) parameters. This topic consists of the following sub-topics: • RTCP Implementation • RTCP Initialization RTCP Implementation Compared to the other protocols implemented by the Net Stack module, RTCP has a different implementation. This difference stems from RTCP's different role in the stack. RTCP is intended to be malleable to provide the information required by a particular application and will often be integrated into the application processing rather than being implemented as a separate layer. The RTCP's implementation is a collection of service routines that helps the application build an RTCP header and analyze the received RTCP frames. Using these functions cannot impose any constraints on the application side because it is the application's responsibility to define the proper use of RTCP. The RTCP implementation does not use SmartDSP OS services in any way. RTCP Initialization As an application layer protocol, RTCP is wrapped with TCP functions. It is up to the user to create RTCP headers and to parse frames with services supported by SmartDSP OS in net_rtcp.h. Uniform Data Packet (UDP) The UDP is a connection-less protocol which does not provide any error detection and recovery. Many Voice over Internet Protocol (VoIP) applications use UDP along with RTP to deliver voice packets from source to destination. The UDP provides channel multiplexing (ports), and checksums the header and payload. This topic consists of the following sub-topics: • UDP Implementation • UDP Initialization • UDP Transmit Process 198 SmartDSP OS User Guide
  • 199. Network Stack IPv6 Network • UDP Receive Process UDP Implementation The UDP protocol implementation has a socket-like API that includes initialization and run-time functions for sending frames. All received UDP frames (all ports) go through the same user-defined function. Consequently, it is users responsibility to multiplex frames according to the sockets. The alignment requirements for UDP differ depending on the hardware. The Ethernet header is not aligned by size. Therefore, when working with FEC (in which 4-byte alignment is required), you must transmit frames with data strictly aligned to 2-byte boundaries. In other cases, data must be aligned to a minimum of 2 bytes. NOTE The UDP stack implementation does not handle alignment requirements. Therefore, you must create the necessary alignment. If you create UDP frames by calling the udpFrameGet() function and supply a buffer pool that is aligned on 4-byte boundaries, the addresses will be aligned on 2-byte boundaries, and the address that Ethernet driver receives will be aligned to minimum of 4 bytes. This is because the udpFrameGet() function uses the udp_offset offset variable to set offset. By default, this value is 42 (UDP + IP + ETHERNET). UDP Initialization During system initialization: 1. The udpInit() function is called by the operating system to initialize the UDP. The udpInit() function takes as parameters the maximum number of sockets that an application can open. 2. Call the inSetUdpCallBack() function to specify a callback function that performs multiplexing of the received frames per port. 3. An UDP socket is created using the udpSocket() function, which returns a socket ID in its parameter. This socket ID is used in all subsequent function calls for data transmission and connection. Refer to SmartDSP OS API Reference Manual for more information on the UDP initialization. UDP Transmit Process To transmit an UDP frame: 1. Create an UDP frame and do any of the following: • Call udpSend() SmartDSP OS User Guide 199
  • 200. Network Stack IPv6 Network • Call udpSendTo() • Call a function, such as udpBufferSend() or udpBufferSendTo() that takes a pointer to data. These two functions will copy the data so that there are no alignment requirements. NOTE The udpSend() and udpBufferSend() functions can be called only for connected sockets (sockets connected using udpConnect()) while udpSendTo() and udpBufferSendTo() can be called for any socket. 2. If udpSend() or udpSendTo() functions return OS_SUCCESS, you should not delete or reuse this frame. If OS_SUCCESS is not returned, it becomes necessary to utilize the frame. 3. Use osFrameBufferSetWithOffset() to connect a buffer to a frame. The offset is used to reserve a space for the stack headers. Another way to create a frame suitable for the UDP is to call the inline function, udpFrameGet(). This function creates a frame for the UDP and returns the data address. To see how to use the udpBufferSend() function to transmit data to a previously connected socket, refer to SmartDSP OS API Reference Manual. NOTE To enhance the performance of the UDP transmit process, it is recommended to call the udpConnect() function before consecutive transmit operations on a socket. This causes the entire UDP-IP header to be cached in the UDP layer. Therefore, the UDP frame can be transmitted directly to BIO. The UDP transmit process does not require any data copies. Therefore, unless check summing is enabled for the UDP layer, core utilization does not depend on the data size. If the first transmit operation is initiated to a new IP address and an ARP request is initiated to this address, only the last frame is queued. This situation can cause frame loss in some cases. Figure 5.7 shows the UDP transmit process. 200 SmartDSP OS User Guide
  • 201. Network Stack IPv6 Network Figure 5.7 UDP Transmit Process UDP Receive Process The UDP can receive frames using a callback function shared by all the UDP sockets. Therefore, you must multiplex all the frames at the UDP level, and delete or use each received frame. If an application identifies that a frame does not belong to it (using the udpGetDestinationPort() function), the application should not delete the frame and should return OS_FAIL from its callback function. The UDP checks the callback function’s return value and if it is ICMP_UNREACH_PORT, the UDP generates the ICMP ‘Destination unreachable’ message. NOTE The udpGetDestinationPort() function returns the destination port for a received UDP frame. If the UDP receive callback function returns OS_SUCCESS for a frame, the application should return the frame to the frame pool by calling the osFrameFree() function. This implementation enables you to create an efficient multiplexing mechanisms at the application level. Also, this implementation uses sockets for transmission and control actions. You can define an UDP callback function using the osSetUdpCallBack() function. Refer to SmartDSP OS API Reference Manual for details on defining an UDP receive callback function. Figure 5.8 shows the UDP receive process. SmartDSP OS User Guide 201
  • 202. Network Stack IPv6 Network Figure 5.8 UDP Receive Process Transmission Control Protocol (TCP) The TCP is a connection-oriented reliable host-to-host protocol designed to transfer a data stream between two hosts with an established connection. The TCP assures that all transmitted data is received in the correct order. This topic consists of the following sub-topics: • TCP Implementation • TCP Initialization • TCP Transmit Process • TCP Receive Process • Closing a TCP Connection TCP Implementation The TCP implementation has a socket-like API; it includes initialization and run-time functions for transmitting packets. All received TCP packets are sent to a user-defined callback function. Data transmissions require an established connection in which the connection requests are user-driven or initiated by a remote peer. 202 SmartDSP OS User Guide
  • 203. Network Stack IPv6 Network The TCP protocol implementation does not handle the frame offset/buffer alignment requirements. You must create buffers with the required alignment and initiate a frame offset with the correct value. The frames created with tcpFrameGet() have a default offset value of 54 (TCP + IP + ETHERNET). If you supply a buffer pool that is aligned on 4-byte boundaries then the addresses (and user data) will be aligned on 2-byte boundaries. TCP Initialization During system initialization: 1. The TCP is initialized by the operating system using the tcpInit() function. The maximum number of sockets that an application can open are specified in the tcpInit() function. The tcpInit() function initializes the IP TCP socket descriptors and TCP descriptors table, and marks all sockets as unused. Refer to SmartDSP OS API Reference Manual for more details. 2. Call the inSetTcpCallBack() function to enable tcp reception and to specify a callback function that performs multiplexing of the received frames per port. 3. You can create a TCP socket by calling tcpSocket(). The tcpSocket() function retrieves an IP TCP socket descriptor and returns a socket ID within its parameters. This ID is used in all subsequent function calls for data transmission and connection. TCP Connection Setup A TCP connection can be established between two hosts either by: • initiating a connection with a remote TCP server — the application functions as a TCP client, or by, • accepting a remote connection request from a remote TCP client — the application functions as a TCP server. The TCP client: • Allocates/creates sockets using tcpSocket(). • Binds sockets to a local interface using tcpBind(). • Connects sockets to a remote peer using tcpConnect(). To see the source code of establishing a TCP connection using a TCP client, refer to SmartDSP OS API Reference Manual. The TCP server: SmartDSP OS User Guide 203
  • 204. Network Stack IPv6 Network • Sends an alert using the tcpReceiveCallBack() function, when a remote host requests a TCP connection. The tcpReceiveCallBack() function has two arguments: socket ID and frame. If the socket ID is NET_TCP_NO_SOCKET, you can call tcpAcceptInfoGet() to check the connection ports and IP addresses. You can accept this connection using the tcpAccept() function, refer to SmartDSP OS API Reference Manual for details. NOTE Use the tcpAcceptInfoGet() function only on the frames that are received with the NET_TCP_NO_SOCKET socket ID. TCP Transmit Process The tcpSend() function is used to transmit an IP TCP frame that has a socket with an established connection to the remote destination. You can call tcpFrameGet() to create a frame for TCP transmission. The tcpFrameGet() function returns the buffer address. When tcpSend() returns OS_SUCCESS, the TCP/IP stack owns the frame. After frame transmission, the TCP/IP stack deletes the frame. To see how to create a new frame and transmit it to a previously connected socket, refer to SmartDSP OS API Reference Manual. You must ensure that the noted frame is not reused or deleted when it is in the possession of the TCP/IP stack. When tcpSend() does not return OS_SUCCESS, the frame is not accepted for transmission by the TCP/IP stack. You can resend or delete the frame immediately. You can also use the tcpBufferSend() function to send the IP TCP frame to the remote destination. You should bind and connect the socket before calling this function. This function copies a buffer into a frame structure and is slower than tcpSend(). To see a sample source code of how to use the tcpBufferSend() function to transmit data to a previously connected socket, refer to SmartDSP OS API Reference Manual. TCP Receive Process You can call the tcpReceiveCallBack() function to receive the incoming TCP frames. After calling tcpReceiveCallBack(), activate the TCP using inSetTcpRxCallBack(). A return of OS_SUCCESS signals the TCP that a frame was used by the application, and the application should release the frame into the pool. To see how to use the TCP receive callback function, refer to SmartDSP OS API Reference Manual. 204 SmartDSP OS User Guide
  • 205. Network Stack IPv6 Network Closing a TCP Connection You can close a TCP connection locally or remotely. To close the connection locally, call the tcpClose() function. A TCP connection is closed remotely by the remote host, which notifies by sending a NULL frame using the receive callback function. After receiving the notification, you can call tcpClose() to release the socket to the unused socket pool. Internet Control Message Protocol (ICMP) Essentially ICMP is a communication protocol between Internet Protocol (IP) implementations on two connected systems. The ICMP is used by the operating system for sending error messages to the machines on network, such as, a requested service is unavailable or a host could not be reached. This topic consists of the following sub-topics: • ICMP Implementation • ICMP Initialization ICMP Implementation ICMP messages are sent using the basic IP header. The icmpError() function is used to transmit an ICMP error message. The following source code shows how to use the icmpError() function: osFrameHeaderPush(frame, IP_UDP_HEADER_SIZE); icmpError((struct ifnet*)&ifn, frame, ICMP_UNREACH, ICMP_UNREACH_ADMIN_PROHIBIT, 0); You also need to use the inSetICMPCallBack() function to set a callback for the ICMP input frames. NOTE The icmpError() function expects an IP frame. Therefore, if you get a frame from the UDP, the offset (IP-UDP) should be removed from this frame before passing it to the icmpError() function. ICMP Initialization To initialize ICMP, user can define a callback for ICMP input packets with inSetICMPCallBack() function. SmartDSP OS User Guide 205
  • 206. Network Stack IPv6 Network Internet Protocol (IP) IP is the primary protocol in the Internet Layer of the Internet Protocol Suite and has the task of delivering distinguished protocol datagrams (packets) from the source host to the destination host solely based on their addresses. For this purpose the IP defines addressing methods and structures for datagram encapsulation. This topic consists of the following sub-topics: • IP Implementation • IP Initialization • IP Transmit Process • IP Receive Process • IP Reassembly IP Implementation Smart DSP OS supports IP packets transmission and reception. IP features like multicasting, fragmentation, Differentiated Services, and IP-options are not supported. IP compilation flags are: • IP_CHECK_ADDRESS_VALIDITY — checks address validity on receiving IP packets. • IP_VALIDATE_LENGTH — checks that the received packets fit to the actual length. • IP_STATISTICS — enable statistics counters for IP. IP Initialization To initialize IP: 1. Create a network interface with ifCreate(). 2. Define default gateway address with inSetDefGateway(). 3. Set IP address with inSetAddr(). NOTE If support is required for additional transportation layer protocols, call the inSetIPCallBack function. The inSetAddr() function assigns the subnet mask of the IP address based on the IP address and the class that it belongs to. For more information, refer to the Addressing section in RFC791. By default, the subnet masks are: 206 SmartDSP OS User Guide
  • 207. Network Stack IPv6 Network • Class A: 255.0.0.0 • Class B: 255.255.0.0 • Class C: 255.255.255.0 You can override the default subnet masks by calling the inSetSubNetMask() function to provide the interface with a new subnet mask. For example, to set a Class C subnet mask: sin.sin_addr.s_addr = 0xFFFFFF00; inSetSubNetMask((struct ifnet*)&ifn,(struct sockaddr*)&sin); IP Transmit Process To transmit IP: 1. ipOutput() is called from upper layers. 2. IP addresses are checked and then etherOutput is called. 3. arpResolve() initiates an ARP request frame. If ARP entry is found, frame is sent with the appropriate MAC address. If the IP destination address is not found in the ARP table, the IP packet is saved for transmission on ARP REPLAY frame reception, see Figure 5.9. SmartDSP OS User Guide 207
  • 208. Network Stack IPv6 Network Figure 5.9 IP Transmit Flow 208 SmartDSP OS User Guide
  • 209. Network Stack IPv6 Network IP Receive Process To receive IP: 1. Frames received by etherInput are pointed to ipInput() if the ethertype is IP. 2. ipInput() verifies that the received packets are with local IP address. 3. Upper layer protocol receive function is called according to the protocol field on the received packet. 4. Unsupported protocols are treated in the user's callback, if any. IP Reassembly SmartDSP OS supports IP reassembly on layer 3 of the SmartDSP OS network stack. NOTE The reassembly process is wrapped by the osHwiSwiftDisable() and the osHwiSwiftEnable() functions. IP reassembly is supported if the packet uses: • Ethernet protocol in layer 2, and • ICMP, UDP, or TCP in layer 4. In addition,: • simultaneous arrival of different fragmented packets is supported. For example, packet1_fragment1, packet2_fragment1, packet2_fragment2 and packet1_fragment1. • fragments are reassembled irrespective of the order in which they are received. • reassembly requires a software timer for each interface determines the number of seconds a packet can live after its first fragment arrives. If the packet is not completely reassembled when the timer expires, the packet is discarded, and an ICMP message is sent (if the first fragment was received). • reassembly offers various error handling mechanisms and software statistics counters This topic consists of the following sub-topics: • Configuration • Basic Flow • Error Handling • Statistics Configuration The configuration of IP reassembly generally involves the following procedures: SmartDSP OS User Guide 209
  • 210. Network Stack IPv6 Network • Enabling Reassembly • Configuring Reassembly • Enabling Error Handling Enabling Reassembly In SmartDSP OS, IP reassembly works only in Multi-buffer Frame mode. Therefore, to have reassembly enabled, make sure that you do not have the following macro defined: FRAME_SINGLE_BUFFER_ONLY In addition, you should use a multi-buffered frame version of the network stack. Configuring Reassembly To configure reassembly, use the inReassemblyInit function. Note that this function should be called for each specific interface. NOTE The inReassemblyInit function requires a single software timer, which is allocated internally by calling the osTimerFind() function. Table 5.3 describes the parameters of the inReassemblyInit function. Table 5.3 Parameters of the inReassemblyInit Function Parameter Description ifp Current interface 210 SmartDSP OS User Guide
  • 211. Network Stack IPv6 Network Table 5.3 Parameters of the inReassemblyInit Function (continued) Parameter Description ip_reassemble_init Initialization data structure with following fields: num_of_frames Number of frames that can be reassembled simultaneously num_of_fragments Number of fragments that can be reassembled simultaneously for all frames. For example, if you expect to receive up to 5 reassembly frames that can hold up to 10 fragments each, you set this value to 50. heap Heap from which to allocate the structures for managing the fragments and the frames timeout_sec Number of seconds a frame is to be kept in the reassembly process after its first fragment arrives. If the frame is not completely reassembled until after the timeout, the frame is released and an ICMP Time Exceeded Reassembly Timeout error message is sent if possible. This is applicable only if the fragment with offset 0 has already been received. Enabling Error Handling SmartDSP OS User Guide 211
  • 212. Network Stack IPv6 Network To enable error handling, define the IP_REASSEMBLY_CHECK_ERRORS macro in the SmartDSPsourcenetincludenet_config_.h file. Remember that checking for errors decreases performance and, therefore, is not recommended if you do not expect errors. 212 SmartDSP OS User Guide
  • 213. Network Stack IPv6 Network Basic Flow The following pseudo-algorithm describes the basic flow of the functionality of IP reassembly. 1. User enables reassembly, and configures the number of frames supported, number of fragments supported, and the timeout period using the inReassemblyInit function. 2. If a fragment arrives in the ipInput function, follow steps 3 to12. A fragment is identified if IP.offset or IP.MF (More Fragments flag) is not equal to zero. 3. Look for a free fragment in the pool of fragments. a. If there are none, discard the packet. Once a timeout occurs for a frame that is in the reassembly process, its fragments are released back into the fragment pool, thus freeing resources. 4. Compare the IP.id, IP.source, IP.destination and IP.protocol fields to determine if the frame that this fragment belongs to is being reassembled already. a. If the reassembled frame that this fragment belongs to has been found, continue working with that reassembled frame. b. Else, look for a free frame in the pool of frames. – If one is found, create a new reassembled frame, initialize all the values and start a timer for this frame. – If there are none, discard the packet. Once a timeout occurs for a frame that is in the reassembly process, its reassembly- frames are released back into the frame pool, thus freeing resources. 5. Add the data length of this fragment to the overall assembled data length of this reassembled frame. 6. If IP.offset equals to zero, it indicates the first fragment. Add the header length of this fragment to the overall assembled data length of the reassembled frame, since the header of the first fragment in the reassembled frame is kept and all other headers are removed. 7. If IP.MF equals to zero, it indicates the last fragment. Set the expected reassembly length to IP.offset + IP.header_length. 8. Add this fragment to a sorted list of all fragments that belong to the reassembled frame. 9. Check for errors, such as: • overlapping fragments • a fragment appears after the fragment defined as last SmartDSP OS User Guide 213
  • 214. Network Stack IPv6 Network • assembled length is larger than maximum IP length. For more information on these errors and their possible resolutions, see Error Handling. 10. If the expected reassembly length equals the overall assembled data length, create the reassembled frame. Add the data from all fragments to the first fragment and remove the Layer II+III headers in all fragments besides the first fragment. 11. Set the IP.length value in the reassembled frame to the overall assembled data length, and set the IP.offset in the reassembled frame to zero. 12. Send the reassembled frame to the next stage according to the IP.protocol value in the ipInput function. Error Handling Error handling is supported when the IP_REASSEMBLY_CHECK_ERRORS macro is defined as ON. Note that timeout errors related to reassembly are not included in this section since such errors are always enabled as they play an integral part in the reassembly process. When you enable error handling using the IP_REASSEMBLY_CHECK_ERRORS macro, the following three errors may be detected: • Overlapping Fragments • Fragment Appears After Fragment That is Defined as Last • Assembled Length is Larger Than Maximum IP Length Overlapping Fragments If sum of the data length and the IP.offset of a fragment is larger than the IP.offset of the next fragment, then the respective fragments are considered as overlapping, and the entire frame is released with all the fragments. Note that the data length is defined as: IP.len–IP.header_length. Fragment Appears After Fragment That is Defined as Last The fragment with the IP.MF flag set as zero is supposed to be the last fragment in the reassembled frame. If a fragment arrives with a higher offset than the fragment defined as last, an error is detected and the frame is released with all the fragments. Assembled Length is Larger Than Maximum IP Length If the assembled length of the reassembled frame is larger than the maximum allowed IP length, that is 65535, an error is detected and the frame is released with all the fragments. 214 SmartDSP OS User Guide
  • 215. Network Stack IPv6 Network Statistics Table 5.4 lists the software statistics counters that IP reassembly in SmartDSP OS supports. Table 5.4 Software Statistics Counters Counter Name Description ips_fragments Total number of fragments received ips_fragdropped Number of fragments discarded or released. This includes fragments discarded because of any error besides a timeout. If an entire frame is discarded, for example due to fragments overlapping, each fragment in the frame increments the counter. ips_fragtimeout Number of fragments released because of a timeout. Each fragment in the released frame increments the counter. ips_reassembled Total number of reassembled packets IP Security (IPSec) Internet Protocol Security (IPsec) is a protocol suite for securing Internet Protocol (IP) communications by authenticating and encrypting each IP packet of a data stream. IPsec also includes protocols for establishing mutual authentication between agents at the beginning of the session and negotiation of cryptographic keys to be used during the session. IPsec is a dual mode, end-to-end, security scheme operating at the Internet Layer of the Internet Protocol Suite or OSI model Layer 3. IPsec can be used for protecting any application traffic across the internet. Applications need not be specifically designed to use IPsec. This topic consists of the following sub-topics: • IPSec Implementation • IPSec Initialization • IPSec Transmit Process • IPSec Receive Process SmartDSP OS User Guide 215
  • 216. Network Stack IPv6 Network IPSec Implementation Net Stack module has targets dedicated for IPSec Support. In Net Stack moduleNet Stack module library supporting IPSec all TCP/UDP output streams are encrypted. Encryption is done with SmartDSP OS SEC driver. It is the user's responsibility to initialize SEC and COP in the application. The support for IPSec goes over the Net Stack module. IP, UDP, and TCP call for IPSec functions and vice versa. IPSec Initialization To initialize IPSec: 1. Initialize SEC. 2. Call to inConfigIPsec(). 3. Setup for specific security parameters is defined with inConfigIPsecSa() (for in and out security configuration it should be called twice). IPSec Transmit Process On output, IPSec is placed between TCP/UDP and IP. Application calls to udpSend()/tcpSend() and the TCP/UDP layer calls for COP abstraction layer with encryption job. After encryption has been finished COP layer calls to espOutputCryptoCb(). The encryption callback calls to ipOutput and frame is sent as an IP packet. Net Stack module does not wait for SEC to finish encryption. The Net Stackstack returns success for transmission request after data has been sent to encryption. Frame transmission over the stack continues once end-of-encryption indication arrives, see Figure 5.10. 216 SmartDSP OS User Guide
  • 217. Network Stack IPv6 Network Figure 5.10 IPSec Transmit Flow Application SmartDSP OS Net Module UDP udp Send IP Sec esp Output espOutputCryptoCb IP ipOutput COP SEC LLD IPSec Receive Process On reception, ipInput calls to espInput. Data is sent for decryption with COP abstraction layer. Net Stack module does not wait for SEC to finish decryption. The frame processing will be continued once encryption callback is executed by COP. The udpInput() is called from espInputCryptoCallback, see Figure 5.11. SmartDSP OS User Guide 217
  • 218. Network Stack IPv6 Network Figure 5.11 IP Sec Receive Flow Application udp Callback SmartDSP OS Net Module UDP udpInput IP Sec IP espInput ipInput CryptoCb etherInput COP BIO SEC LLD UEC LLD Ethernet HW 218 SmartDSP OS User Guide
  • 219. Network Stack IPv6 Network Address Resolution Protocol (ARP) The Address Resolution Protocol (ARP) is responsible for mapping IP addresses to the Media Access Control (MAC) addresses. This topic consists of the following sub-topics: • ARP Implementation • ARP Initialization ARP Implementation The ARP implementation uses an ARP table of a predefined size (MAX_ARP_ENTRIES), which stores the IP and MAC addresses of the machines on network. The API functions that deal with ARP are: • arpInvalidateEntry() — Invalidates ARP entry according to the IP address. The following sample source code shows how to use the arpInvalidateEntry() function: arpInvalidateEntry(ifp, dest.sin_addr.s_addr); NOTE The arpInvalidateEntry() function does not invalidate the TCP/UDP cache for all TCP/UDP sockets. • arpResolve() — Resolves IP address according to hw_addr, which is a pointer to the MAC address. The arpResolve() function returns a MAC address if one exists in the ARP table. Otherwise, the function sends an ARP request to the network stack and returns OS_FAIL. The following sample source code shows how to use the arpResolve() function: uint8_t hw_addr[6]; status = arpResolve(ifp, NULL, 0xDF1F5FA3, hw_addr); • arpAdd() — Adds a new address to the ARP table. To see how to use the arpAdd() function, refer to SmartDSP OS API Reference Manual. • arpProxyAdd() — Adds a new address to the proxy ARP table. • arpAddStatic() - Adds a static entry to ARP table. ARP Initialization To initialize ARP: 1. Create an Ethernet interface with ifCreate(). 2. Call inSetAddr(). SmartDSP OS User Guide 219
  • 220. Network Stack IPv6 Network NOTE arpProxyAdd() should be called for each IP address supported by the application. Management Information Base (MIB) MIB is a type of database used to manage the devices in a communications network. This topic consists of the following sub-topics: • MIB Implementation MIB Implementation Net Stack module partially implements MIB. The implementation is based on RFC2011, RFC2013 and RFC2863. The netMibGet() function should be used to collect the information for a specific group of MIB. 220 SmartDSP OS User Guide
  • 221. 6 Enabling Software An application running on the SmartDSP OS generates many asynchronous and pre- emptable events such as interrupts, tasks, and spinlocks. The number of events, which may reach thousands per second per core, depends on the application. Kernel Awareness Applications using the SmartDSP kernel awareness (KA) tool can log events with only minimal system overhead. KA is a SmartDSP OS component; its graphical interface provides log, interrupt, timer, and queue data event views. KA also helps decode complex memory dumps if an application crashes. The chapter sections explain how to use the KA tool and view related logs: Using SmartDSP OS Kernel Awareness Tool and Viewing KA Logs. Use the SmartDSP OS KA tool for the following: • Directly view the kernel state within the CW IDE. • Precisely view and measure the duration of events. • View tasks usage and bus utilization. • View the order and preemption of events. • View core loads. • Quickly generate configuration files using the configuration tool. • Get event timings in core clock resolution. • View buffer pool and queue usage statistics. SmartDSP OS User Guide 221
  • 222. Enabling Software Kernel Awareness Using SmartDSP OS Kernel Awareness Tool It is necessary to run the CommExpert utility in order to use the SmartDSP OS KA tool. The utility allows KA activation and, thereafter, views—in a KA window or log visualizer—of data collected from the CW Eclipse IDE. Follow these steps to run the utility, activate KA, and access views: 1. Run the CommExpert utility. a. Navigate to the directory <CodeWarrior SC 10.0 Installation directory>SCStarCore_SupportSmartDSPtoolsCommExper t. b. Double click CommExpert.exe to open the CommExpert window (see Figure 6.1). Figure 6.1 CommExpert Window 2. Activate KA (via the CommExpert window). a. In the header menu, select Runtime. b. Choose Kernel Awareness –> Listen to KA plug-ins. c. START dialogue box, complete with the default Server port number (40000), will appear; see Figure 6.2. The CommExpert server listens on this port to get data from CW Eclipse. d. Click Start to initiate the connection with the CommExpert server. 222 SmartDSP OS User Guide
  • 223. Enabling Software Kernel Awareness Figure 6.2 Server Port Number 3. Launch the CW IDE. 4. Open a project in CW. Drag and drop a .project file in the CW IDE. 5. Build and debug a project. a. In the launch file, under Debugger Options, select the OS Awareness tab; see Figure 6.3. b. Select SmartDSP OS from the Target OS pull-down list. c. Under Log, make the following settings: • Mark Log Display. • Under CommExpert Address, enter the IP address1 in the IP Address text box and 40000 in the Port Number text box. • Mark Log Tasks, Log Software Interrupts, Log Hardware Interrupts, Log Spin Locks, and Log Performance. d. Click Apply (located at the bottom of the screen view). e. Click Debug (located at the bottom of the screen view). f. Program downloads to the simulator. g. Debug view appears; see Figure 6.4. h. Execution halts at the first statement of main(). 1.IP address of the machine upon which the CommExpert server is running. SmartDSP OS User Guide 223
  • 224. Enabling Software Kernel Awareness i. Click on the thread shown in the Debug view. The program counter icon located on the marker bar indicates the next statement for execution. Figure 6.3 OS Awareness Tab Figure 6.4 Debug View 224 SmartDSP OS User Guide
  • 225. Enabling Software Kernel Awareness Marker Bar 6. View logs. a. Click Resume . The icon is found in the Debug view under the Debug tab. b. Debugger executes all program statements. c. Debugger completes execution. d. CommExpert window displays incoming connection information, one-by-one, as they are received; see Figure 6.5 for an example of SW Interrupts received. SmartDSP OS User Guide 225
  • 226. Enabling Software Kernel Awareness Figure 6.5 Incoming Connection Information Viewing KA Logs View KA logs in the SmartDSP process window that appears after CommExpert finishes displaying incoming connection information. The SmartDSP process window displays logs for events received after a project has been run. The window (see Figure 6.7) has the following log tabs: event log; system log; tasks; sw interrupts; hw timers; queues; shared queues; and memory. 226 SmartDSP OS User Guide
  • 227. Enabling Software Kernel Awareness event log Tab The event log tab displays the following data; see Figure 6.7. Table 6.1 event log Tab Event Data Description Event names Displays running tasks, SWI and HWI, included in the project. Event statistics Displays data for each thread (SWI/HWI) in the format: • Current Window Utilization: % of time an event is active in the current window. • Entire Log Utilization: % of time an event is active in the entire log. Displayed in closed brackets. • Current Window Number of Activations: number of times an event was activated in the current window. • Entire Log Number of Activations: number of times an event was activated in the entire log. Displayed in closed brackets. Example: 0.00 (0.05%) 0 (192). Event graph Graph showing duration, type, and priority of an event. Left/Right selectors • Help measure the time length of events on the graph. • A running program begins with a background task and then moves to HWI and thereafter to SWI. • The red selector lines, when dragged to a chosen position, let the user measure the time between every flow change. • Figure 6.6 shows selectors placed to measure the time taken by HWI at a given point in the program. Duration • Displays the time period between program tasks. • The units of measurement are configurable. SmartDSP OS User Guide 227
  • 228. Enabling Software Kernel Awareness Table 6.1 event log Tab Event Data Description Core clock • Displays time measurement units. • Manually increase the numbers by clicking on available units: μsec, msec, ticks, Hz, KHz, MHz, and GHz. Load (core utilization) Shows core utilization as follows: • Left side: a selected/visible portion of the log. • Right side: a graph of core utilization for the entire log. Figure 6.6 Left and Right Selectors Figure 6.7 event log Tab 228 SmartDSP OS User Guide
  • 229. Enabling Software Kernel Awareness SmartDSP OS User Guide 229
  • 230. Enabling Software Kernel Awareness system log Tab The system log tab (see Figure 6.8) displays columnar data that the user or OS logged using the function osReportEvent(); this function returns event reports and error status. Table 6.2 system log Tab System Data Description Severity • Designates event severity. – Example: warning or error Event Type • Indicates event type. – Example: error, information, event, and architecture- specific Module • Indicates module within which an event occurred. – Example: DMA, TASK, NET, etc. Event Name • Specific word relating to an event name. – Example: OS_ERR_TSK_BLOCKING Event Code • Numerical code created by an event. – Example: 0x000EFFDC for OS_ERR_TSK_BLOCKING File • Indicates (as a name) the file within which an event occurred. Line • Indicates file line within which an event occurred. Context • [Not in use.] Time • Time at which an event was reported. – Example: 1234 [core cycles] Remarks • User/OS remarks are added to the event report. Figure 6.8 system log Tab 230 SmartDSP OS User Guide
  • 231. Enabling Software Kernel Awareness tasks Tab The tasks tab shows the current state of all tasks in the system; see Figure 6.9. Table 6.3 tasks Tab Tasks Data Description number • Identifier – Example: TASK 0, TASK 1, etc. name • Name – Example: background, task0, task1, etc. status • Usage state – Example: ready, delayed, ready running, and unused. priority • Priority—the lower the number, the higher the priority. – Example: 31, 11, 12 current stack • Current stack pointer location (as an address). – Example: 0x300065f0 top of stack • Top of stack location (as an address). – Example: 0x30006500 stack size • Noted in bytes handler • Task function expiration time • If idle, tasks will resume after a given number of system ticks. Figure 6.9 tasks Tab SmartDSP OS User Guide 231
  • 232. Enabling Software Kernel Awareness sw interrupts Tab The sw interrupts tab displays all SWIs defined in the system. SWIs appearing in this window do not require compilation with a log-enabled OS library; see Figure 6.10. Table 6.4 sw interrupts Tab SWI Data Description name • Identifier – Example: SWI 0, SWI 1, ... address • Location address of the SWI handler. – Example: 86004cE0. handler • SWI function count • Internal variable associated with the SWI. • Generally indicates the number of times the application should execute the SWI. status • Usage state – Example: ready, delayed, ready running, and unused. priority • Priority—the lower the number, the higher the priority. – Example: 31, 11, 12 UID • User ID registerd during osSwiCreate(). – Example: 0000 Figure 6.10 sw interrupts Tab 232 SmartDSP OS User Guide
  • 233. Enabling Software Kernel Awareness hw timers Tab The hw timers tab displays the state of the hardware timers. The only hardware timers handled are those used via the SmartDSP OS HW Timers API; see Table 6.11. Table 6.5 hw timers Tab HW Timers Data Description name • Identifier – Example: OS_HW_TIMER_0000, OS_HW_TIMER_0001... status • Usage state – Example: used and unused mode • Operational mode – Example: periodic, one shot, and free run interval • Interval timing – Example: 0x2710 = number of cycles counted by the timer handler • Function called when the timer expires. Figure 6.11 hw timers Tab SmartDSP OS User Guide 233
  • 234. Enabling Software Kernel Awareness sw timers Tab The sw timers tab shown displays the state of the software timers; see Figure 6.12. Table 6.6 sw timers Tab name • Identifier – Example: OS_TIMER_... status • Usage state – Example: used and unused mode • Operational mode – Example: periodic, one shot, and free run interval • Interval timing – Example: 0x0001 indicates the number of system ticks to reload to the timer after it expires. handler • Function called when the timer expires. value • Current value – Example: 0x00000001 = number of ticks till timer expiration. Figure 6.12 sw timers Tab 234 SmartDSP OS User Guide
  • 235. Enabling Software Kernel Awareness queues Tab The queues tab displays information related to system queues; see Figure 6.13. Table 6.7 queues Tab queue Data Description index • Identifier – Example: 0, 1, 2 ... status • Usage state – Example: used, unused, empty, and full buffer • Buffer address used by the queue. – Example: 0x300093d8. size • Maximum number of items allowed in a queue. items • Number of items currently enqueued Figure 6.13 queues Tab SmartDSP OS User Guide 235
  • 236. Enabling Software Kernel Awareness shared queues Tab The shared queues tab displays queue-related information that is shared by all cores in the system; see Figure 6.14. Table 6.8 shared queues Tab shared queues Data Description index • Identifier – Example: 0, 1, 2 ... status • Usage state – Example: used, unused, empty, and full buffer • Buffer address used by the queue. – Example: 0x300093d8. size • Maximum number of items allowed in a queue. items • Number of items currently enqueued Figure 6.14 shared queues Tab 236 SmartDSP OS User Guide
  • 237. Enabling Software Kernel Awareness memory Tab The memory tab displays information related to all the buffer pools in the system; see Figure 6.15. Table 6.9 memory Tab memory Data Description index • Buffer pool identifier – Example: 0, 1, 2 ... address • Given buffer pool address. block size • Byte size of each block in the buffer pool. free blocks • Available blocks in the buffer pool. – Example: number of memory blocks the manager can allocate without entering an underrun state. Figure 6.15 memory Tab SmartDSP OS User Guide 237
  • 238. Enabling Software Enablement Utilities Enablement Utilities SmartDSP Host Exchange over Asynchronous Transfer (HEAT) and Enhanced Command Line Interface (eCLI) are SmartDSP OS enablement utilities used during application development and runtime. In addition, CommExpert has a utility for initially configuring an application. See SmartDSPtoolsCommExpertdocUser Guide.pdf. This chapter details utilities supported by the SmartDSP OS and how they improve OS performance: • SmartDSP HEAT Runtime Library • eCLI Utility SmartDSP HEAT Runtime Library The SmartDSP HEAT utility provides file access over Ethernet and is compiled in two separate modes: Table 6.10 SmartDSP HEAT Utility Usage Modes Description Override default stdio Allows applications to benefit from all utilities provided function calls. by the stdio library. SmartDSP HEAT utility plugs into the lower layers of the stdio library: • Overrides default CodeWarrior interface (JTAG, using syscall) by calling back into SmartDSP HEAT function calls. • Method requires the following: – User application must link to heat_lib_stdio.elb or heat_lib_stdio_debug.elb. – Further, to use the SmartDSP HEAT stdio library, add -allow-multiple-definition to linker settings. Direct use of SmartDSP • Directly calls SmartDSP HEAT functions HEAT function calls. without linking in the stdio library. • Calls require an application to link heat_lib.elb or heat_lib_debug.elb. 238 SmartDSP OS User Guide
  • 239. Enabling Software Enablement Utilities Table 6.10 SmartDSP HEAT Utility Usage Modes Description Use stdio and SmartDSP • Add include/heat/os_heat_stdio.h in the HEAT with stdio function source file. calls. • Use SmartDSP HEAT functions for stdio lower layers by setting SMARTDSP_HEAT_USES_STDIO to 1 during compilation. Use SmartDSP HEAT with • Call the function osHeatInitialize() both stdio and SmartDSP using a pointer to the structure heat_init_params_t. HEAT function calls. • If heat_init_params_t is NULL, then the osHeatInitialize() function will use default parameters. • If an application needs to write to STDOUT or STDERR, it must also call osHeatConsoleInitialize(). • Application must call osHeatStdioInitialize()to plug into the stdio library. Use HEAT from an • Set poll_connection to TRUE. interrupt handler (ISR). • Specify heat_poll_function; it should call osBioChannelCtrl() to poll—until the server is ready—for incoming packets. SmartDSP HEAT Server The SmartDSP HEAT server is characterized as follows: • DSP runtime library interfaces with a dedicated server running on a remote PC. • Server is delivered as a Windows executable and provides both a makefile and sources. • Files are assumed to be opened in locations relative to the server location. • Server executable is found in SmartDSPtoolsheat_server. • Run the executable with the flag --help to display all the flags supported by the server. SmartDSP OS User Guide 239
  • 240. Enabling Software Enablement Utilities Table 6.11 Server Flags Server Flags Description --help Creates a help message. --thread-count arg (=6) [Default =6] Sets maximum number of server threads. --bind-ip arg [Default: 0.0.0.0] Server IP address. --port arg (=1254) [Default: 1254] Server listens to this port number. --timeout arg (=10) [Default: 10] Sets a time factor—waiting period before an untouched file can be reopened. Useful for recovering files—if the client died or didn’t properly close the file. --log arg (=error) [Default: error] Level of log file details [error, info, debug]. --log-file arg (=log.txt) [Default: log.txt] Log file name --del arg (=no) [Default: no] Deletes existing log file [y(es), n(o)]. Server message format includes the following: date (dd/mm/yyyy), time (hh:mm:ss:mili), and index. For example: 25/04/2010 12:17:05:069 [dbg] Open file SmartSDP_HEAT_README.txt for client succeeded 25/04/2010 12:17:05:100 [ERR] File with hash 3862064 failed to close eCLI Utility eCLI is used for remote debugging of multicore and/or multi-device boards. When combined with standard shell, the result is a powerful remote debug tool that enables users to invoke predefined callback functions over a standard telnet console. All callback functions take two arguments and look similar to this example, int cmd_ecli(int argc, char* argv[]); NOTE Standard shell and eCLI are shipped in a single SmartDSP library. 240 SmartDSP OS User Guide
  • 241. Enabling Software Enablement Utilities Standard Shell The SmartDSP standard shell provides the infrastructure for the following: • parsing text commands received over TCP/IP via a telnet console; and, • returning the results of the invoked functions back to the console. To use this functionality the application must perform the following: 1. Link one of the binaries in SmartDSPlibshell. 2. Call osShellInit() to initialize functionality. 3. Call osShellCommandRegister() to register callback functions that can later be invoked by remote users. SmartDSP provides users with the following standard-shell default commands: Table 6.12 SmartDSP Standard-Shell Default Commands Function/Command Description int cmd_help(int Displays shell help or, if invoked with an argument, the argc, char* help text provided when calling argv[]); osShellCommandRegister(). int cmd_md(int Shows four bytes of memory at a user-specified argc, char* address. argv[]); From: Displays four bytes of the memory at the address specified by the user. int cmd_mm(int Modifies the four bytes of memory to a user-provided argc, char* value at the user-specified address. argv[]); From: Modifies 4 bytes of the memory at the address specified by the user to the value provided by the user. int cmd_info(int Provide textual information that is also obtainable by argc, char* running KA. Refer to the tab sections under “Viewing KA argv[]); Logs” on page 226. eCLI eCLI (extended command line interface) adds two additional commands to those described above: SmartDSP OS User Guide 241
  • 242. Enabling Software Enablement Utilities Table 6.13 SmartDSP eCLI Commands Function/Command Description int cmd_ecli(int • eCLI command is a shell command; it argc, char* argv[]); retrieves user arguments and calls internal sub functions. • CLI capabilities/functionality are extended once a sub program is opened at a user’s CLI. int cmd_reroute(int Sets the device to act as a proxy and reroute eCLI argc, char* argv[]); commands multiple cores and devices. eCLI handles internal global and local variables that may be used to invoke existing functions in the global system table. Local and global variables include the following: Table 6.14 Variables Description e_exec Operates basic commands described in Table 6.12. e_set • Sets system variables to a new value, passed by the user. • It can be used with one parameter to define a value; e.g., e_set $a allocates $a as local variable with a 0 value. • It can be used with two parameters. First parameter is the variable, second parameter is either the value to set or another variable from which to copy the value to set; e.g., e_set var0[var1|val] – Sets var0 with the value of var1 if var 1 is the second parameter. – Sets var0 with the value of val if val is the second parameter. – Value can be specified in the following formats: – 0xNUM — hexadecimal – 0dNUM/NUM — decimal – 0bNUM — binary e_get Prints the variable value; e.g., e_get var. e_free Frees a local variable; e.g., e_free var. 242 SmartDSP OS User Guide
  • 243. Enabling Software Enablement Utilities Function Calls • In eCLI, the function return value is optional. • Function parameters can be numeric, local, or global variables. • Return value can be a local or global variable. For example: e_set $a $a = osMalloc(0x20,0xec9c0000) e_get $a where 0xec9c0000 is the enumeration of OS_MEM_LOCAL. Reroute reroute command reroutes eCLI traffic to a specific core on a specific device. The core and device take a same form “as if” the target had evaluated the functions osGetCoreID()and osGetDeviceID(). For example: reroute 1 0 reroutes an IO towards device 1 core 0. eCLI and Reroute Initialization During initialization, register eCLI and reroute commands as shell commands. The complex reroute command requires registration as well as the following: Table 6.15 eCLI and Reroute Initialization Flow Stage Description Channel initialization For server and clients. Port handling convention Distinguishes between server and client. Reroute initialization • Use the reroute_enable API; it utilizes SmartDSP OS server and client resources. • In the server: – <semaphore * number of sessions> that handles an I/O from machine to clients. – <multiple queues (of 64 bytes per element in the queue) in the size of {number of session} *10> as well as the task that handles the I/O coming from the clients to a machine. • In each client: – <(semaphore + event queue + task) * number of sessions> that handles the TCP connection and the CLI task. SmartDSP OS User Guide 243
  • 244. Enabling Software Enablement Utilities Demo of eCLI Utility Run the eCLI utility through CodeWarrior by following these steps: 1. Compile all required libraries with the LLT flag (export_table); use the LLT flag found in the eCLI demo project. 2. Run the eCLI demo project. 3. Run all project cores. 4. Open telnet using the IP address, 10.0.0.1. 5. Run reroute 1 1 at the command prompt. • reroute command passes eCLI commands to other device cores that are not directly connected to the telnet. • a telnet session opening with core 0 on device 0 will transfer all eCLI commands to core 1 on device 1. 6. Run ecli at the command prompt. • Project functions are ordinarily called with a user’s application code (before compilation). • Using telnet, project functions can be called at runtime. 7. Run the below eCLI commands in the command prompt; see Figure 6.16. e_set $a e_get ecli_demo_counter $a = osTaskActivate(ecli_demo_task_handle) e_get $a osTaskSuspend(ecli_demo_task_handle) e_get ecli_demo_counter 244 SmartDSP OS User Guide
  • 245. Enabling Software Enablement Utilities Figure 6.16 eCLI Command Window • osTaskActivate() activates the task found in the project code. osTaskActivate()displays the following: device ID, core ID, and the CW I/O console counter; see Figure 6.17. • Upon suspension of the task, the e_get ecli_demo_counter returns a result counter to the command window. The counter is not constant; it varies according to the execution time between the osTaskActivate() and osTaskSuspend() functions. 8. Exit eCLI using Ctrl-C + ENTER. Exit reroute (and return to the main core) by typing exit. SmartDSP OS User Guide 245
  • 246. Enabling Software Enablement Utilities Figure 6.17 CodeWarrior I/O Console Window 246 SmartDSP OS User Guide
  • 247. 7 Utilities There are two kinds of SmartDSP OS utilities: Enablement and Verification and Stimulus. IP UDP generator, libSrtp, and MJPEG player are some of the SmartDSP OS verification and stimulus utilities that are used to validate your configurations. These utilities are not used during runtime but only while bringing up the user application. This chapter explains various utilities that SmartDSP OS supports and how these utilities operate to improve the performance of the operating system. The chapter consists of this section: • Verification and Stimulus Utilities Verification and Stimulus Utilities The SmartDSP OS provides the following verification and stimulus utilities: • IP UDP Generator Utility • Real-time Transport Protocol (RTP) Player Utility • libSRTP Utility • MJPEG Player Utility • CommExpert Utility IP UDP Generator Utility The IP UDP generator utility of SmartDSP OS is used to test SmartDSP OS Net Demos. To use the IP UDP generator utility: 1. Connect the board to your machine using an Ethernet cross cable. 2. Set the IP address of the machine to be on the same network as the board is configured. In most Net demos, the board's IP address is hard-coded in the code of the demo application. 3. Run the Net demo. 4. Run IP_UDP_GEN as: IP_UDP_GEN <PC IP Address> <Board IP Address> <Number of iterations> <Min Datagram Size> <Max Datagram Size> For example, SmartDSP OS User Guide 247
  • 248. Utilities Verification and Stimulus Utilities IP_UDP_GEN 223.31.95.163 223.31.95.200 10 800 900 10000 You can now use the IP UDP generator program to send as many IP UDP frames to the board. The board echoes the frames back to the machine, and the IP UDP generator program compares the received data to the transmitted data, and prints the results. Real-time Transport Protocol (RTP) Player Utility The RTP Player utility of SmartDSP OS provides a graphical user interface for transmitting real-time data such as audio, video, and simulation among various applications. The GUI of the RTP Player divides into the following five tabs, each with a specific functionality: • Connection Tab • Record Tab • Codecs Tab • Effects Tab • Statistics Tab Connection Tab The Connection tab of the RTP Player utility (see Figure 7.1) is used for connecting to a DSP. Use the following procedure to specify the settings in the Connection tab to connect to a DSP: 1. Enter the data port of the DSP, in the Data Port text box. The default port number is 2000. 2. Enter the command port of the DSP, in the Command Port text box. The default port number is 1000. These ports help establishing a communication with DSP applications. 3. Enter the IP address of the DSP, in the IP Address text box. The default IP address is 10.0.0.1. 248 SmartDSP OS User Guide
  • 249. Utilities Verification and Stimulus Utilities Figure 7.1 Connection Tab 4. Click Connect to connect to the DSP and Disconnect to disconnect from DSP. Record Tab The Record tab of the RTP Player utility allows you to save a recording of the RTP stream in the .wav format. Use the following procedure to save a recording: SmartDSP OS User Guide 249
  • 250. Utilities Verification and Stimulus Utilities 1. Enter the name of the recorded file in the File name text box, as shown in Figure 7.2 Figure 7.2 Record Tab . 2. Click Record to start the recording and Stop to stop it. The counter shows the elapsed recorded time. Codecs Tab The Codecs tab of the RTP Player utility allows you to select audio codecs to use for compressing or decompressing digital audio data according to a specified audio format. You can select the required codec type and number of channels from the Codec type and Number of channels text boxes respectively (see Figure 7.3). 250 SmartDSP OS User Guide
  • 251. Utilities Verification and Stimulus Utilities Figure 7.3 Codecs Tab Effects Tab The Effects tab of the RTP Player utility allows you to graphically see the audio on the Mono and Stereo channels. Do the following to enter the settings: SmartDSP OS User Guide 251
  • 252. Utilities Verification and Stimulus Utilities 1. Select the required effects by marking the corresponding check box (see Figure 7.4). Figure 7.4 Effects Tab 2. Scroll the slider to the right to increase the intensity of an effect. The minimum intensity of the effect is 1 and the maximum intensity is 10. Statistics Tab The Statistics tab of the RTP Player utility displays the information related to communication statistics (see Figure 7.5). 252 SmartDSP OS User Guide
  • 253. Utilities Verification and Stimulus Utilities Figure 7.5 Statistics Tab Following are the parameters of the Statistics tab: • Connection Status — Displays the connected/disconnected to/from DSP status • Session Source ID — Displays the RTP Session source ID • Total Received RTP Packets — Displays the number of RTP packets that have been received from DSP • Lost RTP Packets — Displays the number of RTP packets that have been lost • Invalid RTP Packets — Displays the number of RTP packets that were corrupted • Avg. RTP Jitter — Displays the average deviation from the proper packet rate. The proper packet rate is 1 packet per 20 msec • Codec Bit Rate — Displays the proper bit rate of the chosen codec type and channel, as described below: – PCM - Stereo - 256 kbit/sec – PCM - Mono - 256 kbit/sec – A-law - Stereo - 128 kbit/sec – A-law - Mono - 64 kbit/sec – U-law - Stereo - 128 kbit/sec – U-law - Mono - 64 kbit/sec SmartDSP OS User Guide 253
  • 254. Utilities Verification and Stimulus Utilities • Sound Device Bit Rate — Displays the real bit rate of the sound device libSRTP Utility The SmartDSP OS libSRTP utility works as a library of the SmartDSP OS. The libSRTP library provides an open-source implementation of the Secure Real-time Transport Protocol (SRTP). SRTP adds a security feature to RTP by providing encryption and authentication to the data transmitted through the RTP. NOTE Please add a note that the utility is based on the open-source source code available at http://srtp.sourceforge.net/srtp.html. The set up and execution of libSRTP needs the net demo configuration. You need to set the default gateway IP address and the Base IP address, as follows: #define DEFAULT_GATEWAY_IP_ADDRESS 0x0A00008A /* 10.0.0.138 */ #define BASE_IP_ADDRESS 0x0A000001 /* 10.0.0.1 */ NOTE The SmartDSP OS IP/UDP stack assumes the standard subnet mask for IP addresses. Therefore, the default demo settings require the 255.255.255.0 subnet mask. The subsequent topics below describe a demo of how to set up the libSRTP utility and then run it. libSRTP Set Up Use the following procedure to set up the libSRTP utility: 1. Configure the board’s dip switches. See the MSC8144ADS Quick Start guide to configure the board. a. On the MSC8144ADS board, make sure that SW 2.1 (HOST) is set to OFF (1). b. On MSC8144ADS rev. PILOT, change SW2.8 to RGMII (ON). NOTE This demo requires the pin MUX6 to work; the board cannot be configured by external dip switches only. 2. Burn the file eeprom_pin_mux6.img into the EEPROM. 3. Configure the reset Word source as EEPROM using the dip switches. 4. Ensure that a GETH network cable is connected to the RJ45 D connector. 254 SmartDSP OS User Guide
  • 255. Utilities Verification and Stimulus Utilities 5. Ensure that the other end of the GETH cable is connected to the GETH card of the computer or switch. libSRTP Execution Use the following steps to execute the libSRTP utility: 1. Run the project, SmartDSPdemosstarcoremsc814xnet_srtpsrtp_projectsrt p.mcp. Ensure that a connection is established by using the ping command. 2. Run the tool, SmartDSPtoolslibSRTPserver.bat. The following lines appear on the screen: >cipher key (hex): a887efd032b38fc0382d0767e9eada58 >salt key (hex): f0d91dd8a14bf79e0aad0038bc93 >auth key (hex): a84c7b14c93ef256bac3856badf6a9218fe5a906 NOTE The above keys correspond to the keys that are used in the demo. These keys are generated by the libSRTP server tool from the master key in the batch file.The same master key also appears in the libSRTP client batch file. You can change the generated keys by changing the master key in both the client and server files. 3. Run the tool, SmartDSPtoolslibSRTPclient.bat. The server tool receives a ‘Hello world’ message. The client tool takes the message from the words.txt file present in the SmartDSP/tools/libSRTP folder. The client encrypts and authenticates the message and sends it to the demo. The demo decrypts the message and changes the first letter each time it is sent. The demo encrypts and authenticates the message and sends it to the server, which decrypts it and prints the result. MJPEG Player Utility The MJPEG Player is used to interact with a DSP and show a stream of motion JPEG. The MJPEG Player sends .bmp files to the MSC81xx DSP and displays the MJPEG stream in the image part of the GUI. Figure 7.6 shows the MJPEG Player window. SmartDSP OS User Guide 255
  • 256. Utilities Verification and Stimulus Utilities Figure 7.6 MJPEG Player Window You can select the file to be sent to the MSC81xx DSP and can make the following choices: • Use the Core enable area to select the cores to participate in the encoding process using the checkboxes. Core 0 is required; others are optional. • Use the Properties area to change the number of frames per second to encode. This allows you to see how it affects the core load and load balancing. • Use the Core color area to select a color for the macro blocks encoded by each core dynamically to show the dynamic load balancing. But you should be aware that this adds to the execution cycles required for frame encoding. 256 SmartDSP OS User Guide
  • 257. Utilities Verification and Stimulus Utilities The loads of all the cores are displayed graphically over time on the bottom right of the window. The current utilization of each of the core is shown graphically in the Application Utilization area of the window. The MJPEG Player also displays the system utilization; that is, cycles used for encoding divided by the number of cycles in the DSP. For example, 4 cores running at 1GHz = 4G cycles. CommExpert Utility The CommExpert utility of the SmartDSP OS is a dialog-based tool. It is used to configure and validate the driver and to generate initialization code for MSC8144 devices. The CommExpert utility allows you to configure specific MSC8144 device modules, which generate C initialization code that runs on the device. The CommExpert utility also provides the correct pin muxing value based on the configured drivers. CommExpert Interface Design The main window of the CommExpert utility displays two panels: • Device view • Status view Device View The Device View panel contains the modules of the device that you select for configuration. The modules are displayed as blocks and you can configure these modules by clicking on them. The panel displays color codes to give information about the status of modules. Figure 7.7 shows the status of the modules displayed in the Device View panel. Figure 7.7 Device View Panel of CommExpert Table 7.1 lists the color codes that the Device View panel displays with the corresponding status of the module. A module’s configuration can have one status listed in the table. SmartDSP OS User Guide 257
  • 258. Utilities Verification and Stimulus Utilities Table 7.1 Status of Modules in Device View Panel Color Code Status Description Gray Not assigned The module is not configured; therefore, no initialization code will be generated for it. Blue Default The module is configured but only with the default values that the CommExpert utility provides. No changes were made to the configuration. Green Configured The module is configured with at least one value different from the default values. Yellow Disabled by hardware The module cannot be configured constraints because the hardware resources use some pins, which are used by another module. White Not supported The block is not supported. In the Device View panel, the silicon devices are divided into the following three categories (Figure 7.8): • Character I/O devices (SPI, UART, I2C) • Buffered I/O devices (UEC 0, UEC 1, SRIO) • Stream I/O devices (TDM) 258 SmartDSP OS User Guide
  • 259. Utilities Verification and Stimulus Utilities Figure 7.8 MSC8144 Device Modules Parts Status View The Status View panel displays a tree structure that contains information about all the configurations made in a project. The information is organized module-by-module where each module has its own structure. Figure 7.9 shows the Status View panel displaying module parameters. SmartDSP OS User Guide 259
  • 260. Utilities Verification and Stimulus Utilities Figure 7.9 Status View Panel - Module Parameters The module parameter window displays the parameter name and its configured value. The parameter values can be displayed as a hexadecimal, decimal, or string value. The first icon from the left side in Figure 7.9 indicates the value of the module parameter. A module parameter can have one of the following values: • Default • Configured The second icon from the left in Figure 7.9 indicates the type of the module parameter. A module parameter can have one of the following types: • Protocol • Device • Driver 260 SmartDSP OS User Guide
  • 261. Utilities Verification and Stimulus Utilities The module parameters are grouped into configuration folders. The Status View tree structure is updated when a configuration is modified. You can delete some of the configuration folders from the Status View panel. A module parameter can belong to one of the following configuration folders: • Removable (can be deleted) • Permanent (cannot be deleted) You can either open a module configuration or delete it by right-clicking on the corresponding configuration folder and selecting the appropriate option from the context menu (Figure 7.10). Figure 7.10 Open/Delete Module Configuration When you select a configuration folder to delete it, a confirmation dialog box appears and if the configuration is removable then it gets deleted. If you try to delete a configuration where interdependency exists, that is another configuration is dependant on it, then an information message appears. Module Design Interface The module design interface or the module configuration window of the CommExpert utility allows you to configure the modules of the MSC8144 device. The module configuration window appears when you right-click on the required module configuration folder in the Status View panel and select the Open option. The module configuration window includes four tabs (Figure 7.11): • Protocol — Include parameters that are specific to that protocol and are independent of the device. • Device — Includes parameters that are specific to a device with their values present in the device registers. • Driver — Includes parameters that the driver introduces to provide better interaction with the device (mainly callbacks). • PinMuxing — Is available only for modules that use pin muxion option 1-8. Some modules can work only with certain pin muxing options. PinMuxing logic prevents SmartDSP OS User Guide 261
  • 262. Utilities Verification and Stimulus Utilities you to choose an incompatible pin muxing option with the correct initialization configuration. Figure 7.11 Module Configuration Window Generally, parameters are logically grouped by their functionality. Figure 7.12 shows an example of the reception parameters grouped together for the UEC module. Figure 7.12 UEC Rx and Tx Parameters Window Workflow of CommExpert This section describes the working of the CommExpert utility for the SmartDSP OS. the basic operations of the CommExpert utility are: • Creating a project • Configuring parameters 262 SmartDSP OS User Guide
  • 263. Utilities Verification and Stimulus Utilities • Generating code Creating a Project Use the following procedure to create a project using the CommExpert utility: 1. Select File > New from the main menu. The New project window appears, as shown in Figure 7.13 Figure 7.13 New Project Window 2. Select the required device family from the Silicon family listbox. 3. Select the required device type for the selected device family from the Silicon type listbox. 4. Select the board constraints for the selected device family from the Board constraints listbox. 5. Select SmartDSP OS from the Operating system drop-down list. 6. Specify a name for the project in the Project name text box. This field is optional. 7. Click OK to display the project in the Device View panel (Figure 7.7). By default, some modules of the selected device display as configured because without these modules, the device will not work. NOTE It is possible to delete the configured system modules even though the device will not work. SmartDSP OS User Guide 263
  • 264. Utilities Verification and Stimulus Utilities Configuring Parameters You can configure the parameters of the module by clicking on the required module. The Module Configuration window for the selected module appears (Figure 7.11). The CommExpert utility contains some restrictions that are imposed by module interdependencies and hardware resource allocation. Before configuring a block, you need to go through all the panels and determine what is required. The CommExpert utility provides module dependencies that exist between the modules while configuring a device. Some modules, such as OS & Cores and UEC, cannot be configured unless others are already configured. The network interface objects defined in the OS & Cores module need an UEC channel to bind to. Therefore, to have network interfaces configured, you must first configure the UEC 0 or UEC 1 channels. All the interdependencies are displayed by the CommExpert utility for the SmartDSP in various forms, such as: • Warning and error messages • Disabled controls on the interface if they cannot be configured • Not allowing deletion from the Status View if a module is in use by another module Figure 7.14 shows an example of driver error message window. The driver errors occur when input values (in the Module Configuration window) tested with the driver are not validated. 264 SmartDSP OS User Guide
  • 265. Utilities Verification and Stimulus Utilities Figure 7.14 Driver Error Message Window Generating Code After configuring the module, use the following procedure to generate the code for that module: SmartDSP OS User Guide 265
  • 266. Utilities Verification and Stimulus Utilities 1. Select Tools > Generate Code to display the Save As dialog box (Figure 7.15) Figure 7.15 Save As Dialog Box 2. Enter the location where you want to save the code on the host system. 3. Type the name of the file in the File name text box and click Save. The file that will be generated is the main initialization file, which contains all the parameters that are configured as structures in the Module Configuration window. The data that the main initialization file contains is different form driver data, such as network interfaces parameters from the OS & Cores module. The other important files that are generated are: • os_config.h — Initializes the SmartDSP OS resources such as stack size, interrupts, and timers • msc814x_config.c — Contains initialization structures used by the driver Apart from these files, the following additional files are also generated containing all the user callbacks configured in the Module Configuration window: • <filename>_ext.h — Contains the definition of the exported data from <filename>.c file 266 SmartDSP OS User Guide
  • 267. Utilities Verification and Stimulus Utilities • <filename>_aux.h — Contains definition for user callbacks that are configured for the drivers • <filename>_aux.c — Contains the implementation of the callbacks defined in <filename>_aux.h NOTE <filename> is the name of the file you specify in the File name text box in the Save As dialog box. On the Driver tab of the Module Configuration window, many modules have a series of user callbacks where you can define your own variables and implementation. These callbacks are put in a file with the name suffixed by aux to the main file name. This file is generated by an auxiliary C file and also an auxiliary header which contains the prototype of the user callbacks. NOTE If the generated auxiliary files already exist on the disk, the user application prompts to make a backup of those files so that you do not lose the existing implementation. The generated files can then be included in CodeWarrior projects. The package comes with a demo test case which has been tested on the device. In the first instance, you can integrate the generated files into this project and then test to see how files run on the device. The code may be generated over the files from the use case project by generating code over the main files of each project file and implicitly rewriting the additional files of this project, which uses the SmartDSP Drivers. The CommExpert utility provides a quick way of opening a recently used project by selecting File > Recent projects from the main menu. SmartDSP OS User Guide 267
  • 268. Utilities Verification and Stimulus Utilities 268 SmartDSP OS User Guide
  • 269. A Using C++ with SmartDSP OS To use C++ in SmartDSP OS, make sure that all the C projects are modified to compile and link under C++. When compiled under C++, your application is able to use all external header files in C++ without interfering with the SmartDSP OS files. NOTE Use SmartDSP OS linker files to enable C++ support when your application uses SmartDSP OS stationery. To modify SmartDSP OS linker files do the following steps: 1. To define ENABLE_EXCEPTION, add ENABLE_EXCEPTION=0x1 in the LCF file or add Xlnk -DENABLE_EXCEPTION=0x1 in the linker command line. Enables exception handling to work properly. 2. To support C++ symbols, add the following lines to local_map_link.l3k: _cpp_staticinit_start= originof(".staticinit"); _cpp_staticinit_end= endof(".staticinit"); __exception_table_start__ = (ENABLE_EXCEPTION) ?originof(".exception_index"):0; __exception_table_end__ = (ENABLE_EXCEPTION) ?endof(".exception_index"):0; 3. Add .exception segment to local_map_link.l3k, see Listing A.1. Listing A.1 Adding Support for Exception Handling SECTIONS { descriptor_local_data { .oskernel_local_data .data ramsp_0 .oskernel_rom .rom .exception SmartDSP OS User Guide 269
  • 270. Using C++ with SmartDSP OS .exception_index ….. 4. Add .unlikely segment to os_msc815x_link.l3k, see Listing A.2. Listing A.2 Adding .unlikely Segment descriptor_os_kernel_text { .osvecb .oskernel_text_run_time .oskernel_text_run_time_critical .oskernel_text_initialization .unlikely .text .private_load_text .default .intvec ....... 5. Enable the compiler rtlib at os_msc815x_link.l3k: #define USING_RTLIB 1 6. To enable exception handling, type –Cpp_exceptions on in the To Shell field, see Figure A.1. Figure A.1 Properties Window—Tool Settings Page 7. For more information on enabling exception handling, refer to How to Compile C Source Files section of the StarCore C-C++ Compiler User Guide. 270 SmartDSP OS User Guide
  • 271. Index A Configuring parameters 264 Activating KA 222 Creating a project 263 Activating task 38 Generating code 265 Architecture 10 CommExpert utility 257 ARP 219 conditional assembly 222 Implementation 219 COP 99 Initialization 219 COP Initialization Workflow 89 Asynchronous intercore messaging 63 System 89 User Application 90 B COP Layers 89 COP LLD 89 Background task 40, 69, 71 COP Runtime Workflow 90 BIO Initialization Workflow 84 Job Dispatch 90 System 84 COP Serializer 89 User Application 85 Coprocessor (COP) Module 88 BIO Layers 84 Create a queue 60 BIO LLD 84 Creating a new task 37 BIO Runtime Workflow 87 Receive 88 Transmit 87 D BIO Serializer 84 Data ID,DID 33, 34 Buffer Management 47 Device View panel 257 Buffered I/O Module 83 DHCP Implementation 195 C Initialization 196 DMA 99, 100 Cache configuration 58 Doorbell 167, 168 Cache sweep commands 57 Doorbell API 139 Asynchronous 58 Drivers 11 Synchronous 58 Caches 57 Character I/O (CIO) Module 93 E CIO 99 eCLI 241 CIO Initialization Workflow 94 eCLI Utility 240 System 94 Enablement Utilities 238 User Application 95 Event queues 71 CIO Layers 94 Event Semaphores 69 CIO LLD 94 Extension Point CIO Runtime Workflow 95 Documentation 269 Receive 96 Transmit 96 F CIO Serializer 94 Features 9 CommExpert SmartDSP OS User Guide 271
  • 272. G Gigabit Ethernet (GETH) 115 H Hardware Abstraction Layers (HAL) 81 Conceptual Model 81 Conceptual Workflow 83 Hardware interrupts, HWI 27, 40, 68 Hardware timers 78 Configuration 79 Heap 45 Heap structure 46 I ICMP 205 Implementation 205 Initialization 205 Initialization 159 Initialization and Start Up 14 Intercore message queues 66 Configuration 66 Intercore Messaging 62 Intercore messaging configuration 63 Intercore Options 67 Interrupt Service Routines,ISR 42 Interrupt Sources 26 Interrupt Types 27 Interrupts 26 Introducing Kernel Awareness 221 IP Implementation 206 Initialization 206 Reassembly 209 Receive 209 Transmit 207 IP UDP Generator Utility 247 IPSec 215 Implementation 216 Initialization 216 Receive 217 Transmit 216 272 SmartDSP OS User Guide
  • 273. K Kernel 11 Kernel Components 25 Kernel Introduction 25 L libSRTP Execution 255 libSRTP Setup 254 libSRTP Utility 254 Linker Command File, LCF 52 Linker Guidelines 16 M MAPLE 150, 159 MAPLE driver Runtime 162 MAPLE-B 150 Initialization 159 Maskable Interrupt 26 Memory Allocation 45 Memory Management Unit, MMU 50 Memory Manager 43 MIB 220 Implementation 220 MMU Configuration 55 MMU context 34, 53, 55 Abstraction 53 Creation 54 MMU exceptions 56 MMU Features 51 MMU Segment 34 MMU segment 51, 55 Abstraction 51 Creation 52 Module Configuration window 261 MSI 141 N Net Stack 12, 183 ARP 219 Compile-time Configuration 187 Conceptual Model 183 DHCP 194 SmartDSP OS User Guide 273
  • 274. ICMP 205 Initialization 186 IP 206 IPSec 215 MIB 220 RTCP 198 RTP 196 SRTP 196 Supported Protocols 188 TCP 202 UDP 198 Non-Maskable Interrupt 26 O OCeaN DMA 177, 182 P PEX 141 Platforms 10 Private queues 60 Program ID,PID 33, 34 Protocols 188 Q Queues 59 R Real-time Transport Protocol (RTP) Player Utility 248 Reroute 243 RIONET 164 RIONET transmit 166 RTCP 198 Implementation 198 Initialization 198 RTP 196 Implementation 197 Initialization 197 RTP player Codecs tab 250 Connection Tab 248 Effects tab 251 Record tab 249 Statistics tab 252 274 SmartDSP OS User Guide
  • 275. RTP player utility 248 S Scheduler 32 Scheduler operation 33 Shared queues 60 SIO 99 SIO Initialization Workflow 91 System 92 User Application 92 SIO Layers 91 SIO LLD 91 SIO Runtime Workflow 93 SIO Serializer 91 SmartDSP HEAT Utility 238 SmartDSP HEAT utility 238 SmartDSP OS driver 99 SmartDSP OS Utilities Verification and stimulus 247 Software interrupts, SWI 40, 68 Software Timers 74 Software timers 73 Configuration 75 Spinlocks 42 SRTP 196 Status View panel 259 Suspending task 38 Synchronized I/O (SIO) Module 91 Synchronous intercore messaging 62 T Task States 39 Tasks 33 TCP 202 Closing Connection 205 Connection Setup 203 Implementation 202 Initialization 203 Receive 204 Transmit 204 TDM driver Initialization 179 Transmit/Receive 178 Time Division Multiplexing (TDM) 163, 177 SmartDSP OS User Guide 275
  • 276. Types of drivers 99 Types of SmartDSP OS Drivers 99 U UART 179 UART driver Receive 181 UDP 198 Implementation 199 Initialization 199 Receive 201 Transmit 199 UEC 115 UEC frames Multi-buffered 116 Single-buffered 116 Utilities 13 Utilities of SmartDSP OS 247 V Verification and stimulus utilities 247 Viewing KA Logs 226 Event Log Tab 227 HW Timers Tab 233 Memory Tab 237 Queues Tab 235 Shared Queues Tab 236 SW Interrupts Tab 232 System Log tab 230 Tasks Tab 231 276 SmartDSP OS User Guide