/* 
 * Copyright (c) 2010
 * Texas Instruments
 *
 *  All rights reserved.  Property of Texas Instruments
 *  Restricted rights to use, duplicate or disclose this code are
 *  granted through contract.
 * 
 * */

/*
 * For RTA logging, refer to http://processors.wiki.ti.com/index.php/Adding_RTA_to_Your_BIOS_6_Application
*
*/


/* Specify startup function that sets local MultiProc id */
var Startup = xdc.useModule('xdc.runtime.Startup');
var LoggingSetup = xdc.useModule('ti.uia.sysbios.LoggingSetup');
Startup.firstFxns.$add('&setMyId');
                           
/* 
 *  The SysStd System provider is a good one to use for debugging 
 *  but does not have the best performance. Use xdc.runtime.SysMin
 *  for better performance.
 */
var System   = xdc.useModule('xdc.runtime.System');
var SysStd   = xdc.useModule('xdc.runtime.SysStd');
System.SupportProxy = SysStd;

/* Enable modules used by this application */
var HeapBufMP   = xdc.useModule('ti.sdo.ipc.heaps.HeapBufMP');
var HeapMemMP   = xdc.useModule('ti.sdo.ipc.heaps.HeapMemMP');
var Cache = xdc.useModule('ti.sysbios.family.c66.Cache');

/* BIOS/XDC modules */
var Task                = xdc.useModule('ti.sysbios.knl.Task');
var Memory              = xdc.useModule('xdc.runtime.Memory');
var HeapMem             = xdc.useModule('ti.sysbios.heaps.HeapMem');

var BIOS = xdc.useModule('ti.sysbios.BIOS');
//The BIOS module will create the default heap for the system
// Note: A 32KB block was allocated for default runtime heap in the
// M2 configuration file, saw an example .cfg that did it with less code.
BIOS.heapSize = 0x8000;

// This is needed so our abort handler gets a filename. By default, the filename
// is NULL. See http://processors.wiki.ti.com/index.php/SYS/BIOS_FAQs
BIOS.libType = BIOS.LibType_Custom;
BIOS.customCCOpts += " -Dxdc_FILE=__FILE__ ";

// If we use Timestamp_getFreq() in MulticoreMgr.c instead of the 
// 1000000000 constant, we will need this module.
//var Timestamp           = xdc.useModule('xdc.runtime.Timestamp');

/*
 * The following is used to specify the CPU frequency for our "tick"
 * time.
 */
BIOS.cpuFreq.lo = 1000000000;

// BZ_2014 note: this was a C64-specific timer module before
var Timer               = xdc.useModule('ti.sysbios.hal.Timer');
var CpIntc              = xdc.useModule('ti.sysbios.family.c66.tci66xx.CpIntc');


/*  First argument of setConfig tells the core its core id
	Pass "null" as the first argument defers core id setting.
	This is done because the .cfg is applied to every core and putting in "CORE{#}" would assign
	them the same core id. Core id setting is done by the setMyId() function calling APIs from
	the MultiProc module. setMyID() is called before main() by adding it through "Startup.firstFxns.$add('&setMyId');"
	The second argument of MultiProc.setConfig() reveals all possible core ids */
var MultiProc   = xdc.useModule('ti.sdo.utils.MultiProc');
// TODO: change to 4 cores for phoenix 
MultiProc.setConfig(null, ["CORE0", "CORE1", "CORE2",  "CORE3", "CORE4", "CORE5", "CORE6", "CORE7"]);

/* Synchronize all processors (this will be done after Ipc_start) */
/* Ipc.ProcSync_PAIR means core attachments will be done manually as opposed to 
   Ipc.ProcSync_ALL, which attaches each core to every other core automatically
   Note: When cores are attached manually, they must be done in the following order:
         (1) All cores attach to shared memory region owner first
         (2) Cores attach to each other in increasing order (Core 1 does attaching, then Core 2, etc.)*/
var Ipc         = xdc.useModule('ti.sdo.ipc.Ipc');
Ipc.procSync = Ipc.ProcSync_PAIR; 

/* QMSS/CPPI memory settings */

/* Load and use the CPPI and QMSS Low Level Drivers to initialize QMSS */
/* WRZ - REMOVED QMSS STUFF TEMPORARILY
var Qmss = xdc.loadPackage('ti.drv.qmss'); 
var Cppi = xdc.loadPackage('ti.drv.cppi'); 
 END OF REMOVED BLOCK */

//Allocated section in MSMCRAM for QMSS LLD
Program.sectMap[".qmss"] = new Program.SectionSpec();
Program.sectMap[".qmss"] = "MSMCSRAM";
//Allocate section in MSMCRAM for CPPI LLD (Needed by QMSS LLD)
Program.sectMap[".cppi"] = new Program.SectionSpec();
Program.sectMap[".cppi"] = "MSMCSRAM";
//Allocate section for descriptors
Program.sectMap[".desc"] = new Program.SectionSpec();
Program.sectMap[".desc"] = "MSMCSRAM";

Program.sectMap["platform_lib"] = new Program.SectionSpec();
Program.sectMap["platform_lib"] = "L2SRAM";

/*********** WRZ - TRYING TO GET THE FED WORKING **************/
var MessageQ    = xdc.useModule('ti.sdo.ipc.MessageQ');
/*********** WRZ - END OF TRYING BLOCK **************/

/* 
 WRZ - THIS IS QMSS IPC STUFF - COMMENTED OUT TO SEE IF I CAN GET THE FED RUNNING
//Delegate QMSS as transport mechanism for MessageQ 
var MessageQ    = xdc.useModule('ti.sdo.ipc.MessageQ');
var Settings = xdc.useModule('ti.sdo.ipc.family.Settings');
var TransportQmss = xdc.useModule('ti.transport.ipc.qmss.transports.TransportQmss')
var TransportQmssSetup = xdc.useModule('ti.transport.ipc.qmss.transports.TransportQmssSetup');

// The following MessageQ setup is ported from TI QMSS IPC/MessageQ example
MessageQ.SetupTransportProxy = xdc.useModule(Settings.getMessageQSetupDelegate());
MessageQ.SetupTransportProxy = TransportQmssSetup;


TransportQmssSetup.descMemRegion = 0;
Program.global.descriptorMemRegion = TransportQmssSetup.descMemRegion;

// Any variable defined in this cfg file by Program.global, CCSv5 creates these defines in the *_p64P.h header file. 
// You get these #defines by adding
// #include <xdc/cfg/global.h> in your "C" file.

// uses QMSS internal memory for the first 16k descriptors. (without using MSMC or DDR memory for indexing)
// note: numDescriptors * descriptorSize >= 64K (If the product is less than 64K, IPC will not work properly.)
Program.global.numDescriptors = 512;
Program.global.descriptorSize = 256;// Determines IPC Message Size for Monolithic Descriptors

//Setting some QMSS parameters
TransportQmss.numDescriptors = Program.global.numDescriptors;
TransportQmss.descriptorIsInSharedMem = true;
TransportQmss.descriptorSize = Program.global.descriptorSize;
TransportQmss.useAccumulatorLogic = false; // accumulate x number of messages before notifying queue owner
TransportQmss.pacingEnabled = false;
TransportQmss.intThreshold = 1; // how many messages to accumulate before notifying queue owner
TransportQmss.timerLoadCount = 0;
TransportQmss.accuHiPriListSize = 0;

 END OF COMMENTED SECTION
*/

/*Declaring HeapIDs, the shared regions whom they represent will be declared later in the file
  The HeapIDs will be used to register shared region with HeapMem module in HeapMemMgr.c*/
Program.global.SL2HEAPID  = 0;
Program.global.DDRHEAPID  = 1;
Program.global.LL2HEAPID  = 2;
Program.global.SL2HEAP2ID = 3;

Program.global.CFG_SL2_IPC_MSG_BASE       = 0x0c000000;
Program.global.CFG_SL2_IPC_MSG_SIZE       = 0x00010000;
Program.global.CFG_SL2_BASE               = 0x0c010000;
Program.global.CFG_SL2_SIZE               = 0x00370000;
Program.global.CFG_HEAPLL2_SIZE           = 0x00046100;       // all of LL2 (512KB) minus L2SRAM and L2Cache (128KB)

//---------- Total DDR on EVM = 512 MB ------------
Program.global.DDR_START_ADDRESS         = 0x80000000;
Program.global.DDR_END_ADDRESS           = 0x9FFFFFFF;


// DDR memory is separated into CINE, uncached region (interface and other uncached data sections), DDR Heap, DDR vars & code
// RTSC setup is as following:
// 0x8000_0000 to 0x80FF_FFFF : spDsp_Interface.h, noncached data, diagnostics, and params
// 0x8100_0000 to 0x903B_FFFF : DDR heap and the other sections associated with DDR in Custom_xxx.xdl file.
// 0x903C_0000 to 0x9FFF_FFFF : CINE 

Program.global.CFG_NUM_CINE_FOVS        = 2;

// EVM configuration for CINE memory 219 MB for twod/color, 32 MB for sweep, 1 MB for ECG (only support 1 FOV in EVM setting)
// Refer to HeapMemMgr.c for the CINE memory allocation.  (Note that: CFG_NUM_CINE_FOVS = 2)
Program.global.CFG_HEAP_FRAME_CINE_SIZE  = 0x06DA0000;       // 219.25 MB = 109.625 MB * NUM_CINE_MEM_SECTION
Program.global.CFG_HEAP_SWEEP_CINE_SIZE = 0x01000000;       //     32 MB = 16 MB * NUM_CINE_MEM_SECTION
Program.global.CFG_HEAP_ECG_CINE_SIZE   = 0x00080000;       //      1 MB = 0.5 MB * NUM_CINE_MEM_SECTION

// DDR Heap setup:
// 224 MB (DDR HEAP) = 512 MB (MAX DDR SIZE @ EVM) - 252MB (CINE MEMORY) - 16MB (uncached DDR) - 20 MB (for DDR vars and code or left over)
Program.global.CFG_DDR_HEAP_BASE  = 0x81000000;
Program.global.CFG_DDR_HEAP_SIZE  = 0x0E000000;   // => 224 MB
Program.global.CFG_CINE_HEAP_BASE  = 0x903C0000;
Program.global.CFG_CINE_HEAP_SIZE  = 0xFC40000;   // => 252 MB


/* 
 *  Define the shared regions. The IPC modules use this
 *  to make portable pointers. All processors need to add this
 *  call with their base address of the shared memory region.
 *  If the processor cannot access the memory, do not add it.
 *  NOTE: On c6678, region 0 needs to be placed SL2 RAM because of the
 *  requirement that all GateMP created on this device use SL2 RAM
 *  shared memory. 
 *  (BZ_2014 note: it's possible that uncached DDR could also be used 
 *   here. I don't know what GateMP is.)
 */ 

/* Shared Memory base address and length */
var SHAREDMEMSL2        = Program.global.CFG_SL2_IPC_MSG_BASE;
var SHAREDMEMSL2SIZE    = Program.global.CFG_SL2_IPC_MSG_SIZE;

/* SL2 Shared Memory base address and length */
var SharedRegionSL2 = xdc.useModule('ti.sdo.ipc.SharedRegion');
SharedRegionSL2.setEntryMeta(Program.global.SL2HEAPID,
    { base: SHAREDMEMSL2, 
      len:  SHAREDMEMSL2SIZE,
      ownerProcId: 0,
      isValid: true,
      cacheLineSize: 64, /* need 64B to get pass IPC_attach phase, and it is okay with our 256B message size in our code */
      createHeap: true,
      name: "SL2_IPC",
    });

/* Shared Memory base address and length */
var SHAREDMEM2SL2        = Program.global.CFG_SL2_BASE;
var SHAREDMEM2SL2SIZE    = Program.global.CFG_SL2_SIZE;

/* SL2 Shared Memory base address and length */
var SharedRegion2SL2 = xdc.useModule('ti.sdo.ipc.SharedRegion');
SharedRegion2SL2.setEntryMeta(Program.global.SL2HEAP2ID,
    { base: SHAREDMEM2SL2, 
      len:  SHAREDMEM2SL2SIZE,
      ownerProcId: 0,
      isValid: true,
      cacheLineSize: 128, /* L2 cache line size: 128B */
      createHeap: true,
      name: "SL2_HEAP",
    });

/* DDR Shared Memory base address and length */
var SHAREDMEMDDR           = Program.global.CFG_DDR_HEAP_BASE;
var SHAREDMEMSIZEDDR       = Program.global.CFG_DDR_HEAP_SIZE;

var SharedRegionDDR = xdc.useModule('ti.sdo.ipc.SharedRegion');
SharedRegionDDR.numEntries = 4;
SharedRegionDDR.translate = false;    
SharedRegionDDR.setEntryMeta(Program.global.DDRHEAPID,
    { base: SHAREDMEMDDR, 
      len:  SHAREDMEMSIZEDDR,
      ownerProcId: 0,
      isValid: true,
      cacheLineSize: 128, /* L2 cache line size: 128B */
      createHeap: true,
      cacheEnable: true, /*This should reflect the cacheability of memory region. This does NOT set the cacheability*/
      name: "DDR_HEAP",
    });    
/* DDR Cine Memory */
var FRAMEHEAPSIZE		    = Program.global.CFG_HEAP_FRAME_CINE_SIZE;
var SWEEPHEAPSIZE			= Program.global.CFG_HEAP_SWEEP_CINE_SIZE;
var ECGHEAPSIZE				= Program.global.CFG_HEAP_ECG_CINE_SIZE;
/* Frame Heap FOV 1 */
var HeapMem_FrameFov1 = xdc.useModule('ti.sysbios.heaps.HeapMem');
var HeapMemParams_FrameFov1 = new HeapMem_FrameFov1.Params;
HeapMemParams_FrameFov1.size = FRAMEHEAPSIZE;
HeapMemParams_FrameFov1.sectionName = ".sect_cine_data";
Program.global.gHeapMemFrameCineFovOneHandle = HeapMem.create(HeapMemParams_FrameFov1);
/* Frame Heap FOV 2 */
var HeapMem_FrameFov2 = xdc.useModule('ti.sysbios.heaps.HeapMem');
var HeapMemParams_FrameFov2 = new HeapMem_FrameFov2.Params;
HeapMemParams_FrameFov2.size = FRAMEHEAPSIZE;
HeapMemParams_FrameFov2.sectionName = ".sect_cine_data";
Program.global.gHeapMemFrameCineFovTwoHandle = HeapMem.create(HeapMemParams_FrameFov2);
Program.global.CINE_HEAP_FRAME_FOV2_BASE = Program.global.CFG_CINE_HEAP_BASE + FRAMEHEAPSIZE;
/* Sweep Heap FOV 1 */
var HeapMem_SweepFov1 = xdc.useModule('ti.sysbios.heaps.HeapMem');
var HeapMemParams_SweepFov1 = new HeapMem_SweepFov1.Params;
HeapMemParams_SweepFov1.size = SWEEPHEAPSIZE;
HeapMemParams_SweepFov1.sectionName = ".sect_cine_data";
Program.global.gHeapMemSweepCineFovOneHandle = HeapMem.create(HeapMemParams_SweepFov1);
Program.global.CINE_HEAP_SWEEP_FOV1_BASE = Program.global.CINE_HEAP_FRAME_FOV2_BASE + FRAMEHEAPSIZE;
/* Sweep Heap FOV 2 */
var HeapMem_SweepFov2 = xdc.useModule('ti.sysbios.heaps.HeapMem');
var HeapMemParams_SweepFov2 = new HeapMem_SweepFov2.Params;
HeapMemParams_SweepFov2.size = SWEEPHEAPSIZE;
HeapMemParams_SweepFov2.sectionName = ".sect_cine_data";
Program.global.gHeapMemSweepCineFovTwoHandle = HeapMem.create(HeapMemParams_SweepFov2);
Program.global.CINE_HEAP_SWEEP_FOV2_BASE = Program.global.CINE_HEAP_SWEEP_FOV1_BASE + SWEEPHEAPSIZE;
/* ECG Heap FOV 1 */
var HeapMem_EcgFov1 = xdc.useModule('ti.sysbios.heaps.HeapMem');
var HeapMemParams_EcgFov1 = new HeapMem_EcgFov1.Params;
HeapMemParams_EcgFov1.size = ECGHEAPSIZE;
HeapMemParams_EcgFov1.sectionName = ".sect_cine_data";
Program.global.gHeapMemEcgCineFovOneHandle = HeapMem.create(HeapMemParams_EcgFov1);
Program.global.CINE_HEAP_ECG_FOV1_BASE = Program.global.CINE_HEAP_SWEEP_FOV2_BASE + SWEEPHEAPSIZE;
/* ECG Heap FOV 2 */
var HeapMem_EcgFov2 = xdc.useModule('ti.sysbios.heaps.HeapMem');
var HeapMemParams_EcgFov2 = new HeapMem_EcgFov2.Params;
HeapMemParams_EcgFov2.size = ECGHEAPSIZE;
HeapMemParams_EcgFov2.sectionName = ".sect_cine_data";
Program.global.gHeapMemEcgCineFovTwoHandle = HeapMem.create(HeapMemParams_EcgFov2); 
Program.global.CINE_HEAP_ECG_FOV2_BASE = Program.global.CINE_HEAP_ECG_FOV1_BASE + ECGHEAPSIZE;

/* 
 * Clock related module
 * See C:\Program Files\Texas Instruments\bios_6_31_04_27\docs\cdoc\index.html
 * ti.sysbios.knl.Clock. 
 */
var ti_sysbios_knl_Clock = xdc.useModule('ti.sysbios.knl.Clock');
// The default is 1000 microseconds. Specify it so that we capture
// any changes to this value. Note, this effects our Task_sleep()'s that 
// are specified in ticks and not time.
// (@todo - we should specify sleeps in time not ticks)
ti_sysbios_knl_Clock.tickPeriod = 1000; //1ms.

Program.sysStack = 0x1000;
Program.stack = 0x1000;

var ti_sysbios_knl_Swi = xdc.useModule('ti.sysbios.knl.Swi');
// BZ_2014 note: the next two lines had 'c64p' for the 6472 version. 
//   It's unclear whether the newly renamed modules exist at all, or where they 
//   can be found if they do not.
var ti_sysbios_hal_Hwi = xdc.useModule('ti.sysbios.hal.Hwi');
// BZ_2014 note: there is no ti.sysbios.hal.Exception or any other generic Exception module. 
//  It's C64p or nothing, so it's nothing.
// var Exc = xdc.useModule('ti.sysbios.hal.Exception');


/* Create default logger for the whole system. */
var LoggerBuf = xdc.useModule('xdc.runtime.LoggerBuf');
var loggerBuf0Params = new LoggerBuf.Params();
loggerBuf0Params.numEntries = 128;
loggerBuf0Params.instance.name = "loggerBuf0";
loggerBuf0 = LoggerBuf.create(loggerBuf0Params);
Program.global.hLogger = loggerBuf0;

 print("Application Logger num records: " + loggerBuf0Params.numEntries);
 print("Application Logger Entry Size: " + LoggerBuf.Entry.$sizeof());
 print("Application Logger Size (MAUs): " + ( loggerBuf0Params.numEntries *  LoggerBuf.Entry.$sizeof()));
 print(BIOS.customCCOpts);
// Log_prints are turned on/off by setting the USER value below to
// RUNTIME_OFF
//
// Logging       Diags_USER
// ---------     ----------
// Framework          1   Includes logs generated by interaction with the host.
// Twod               2
// color              3
// Doppler/MMode      4   Combining since they will not be run at the same time.
// Error              5
// SRIO               6

// Set log_print masks to RUNTIME_ON so that we can turn them on/off realtime in the code.
// Eg: 
// - to turn diages_USER1 off: Diags_setMask( "xdc.runtime.Main-1" );
// - to turn diages_USER1 on: Diags_setMask( "xdc.runtime.Main+1" );
var Main                = xdc.useModule('xdc.runtime.Main');

/* Logger buffer modules */
var Defaults =  xdc.useModule('xdc.runtime.Defaults');
var Diags =     xdc.useModule('xdc.runtime.Diags');

Main.common$.diags_USER1 = Diags.RUNTIME_ON;
Main.common$.diags_USER2 = Diags.RUNTIME_ON;
Main.common$.diags_USER3 = Diags.RUNTIME_ON;
Main.common$.diags_USER4 = Diags.RUNTIME_ON;
Main.common$.diags_USER5 = Diags.RUNTIME_ON;
Main.common$.diags_USER6 = Diags.RUNTIME_ON;

// logger buf code resides in DDR
Program.sectMap[".sysbios: { *.*(.text:*xdc_runtime_LoggerBuf*) }"] = "DDR";

// BZ_2014 note: this was Custom_M2_6472_p64P_x.xdl... looks like the name of this file is under our direct control.
Program.sectionsTemplate = "../Custom_M2_6674_p66_x.xdl"; 
Program.sectionsExclude = "^\.const$|^\.text$|^\.boot_entry$|^\.cio$|^\.far$|^\.sysmem$|^\.bss$|^\.pinit$|^\.cinit$|^\.switch$|^\.data$|^\.stack$|^\.vecs$|^\.heapll2$";   

var Error = xdc.useModule('xdc.runtime.Error');
//Error.raiseHook = "&ErrorMgr_tiSysbiosBiosErrorRaiseHook";

var Semaphore = xdc.useModule('ti.sysbios.knl.Semaphore');
Semaphore.supportsEvents = false;

var Hwi = xdc.useModule('ti.sysbios.hal.Hwi');  

var GateMP = xdc.useModule('ti.sdo.ipc.GateMP');
GateMP.RemoteCustom1Proxy = xdc.useModule('ti.sdo.ipc.gates.GateMPSupportNull');

// This text is needed to give us the ability to turn realtime print_logs on/off.
var Text = xdc.useModule('xdc.runtime.Text');
Text.isLoaded = true; 

print("isLoaded: " + Text.isLoaded);
Text.$seal("isLoaded")
LoggingSetup.loadTaskLogging = true;
LoggingSetup.loadSwiLogging = true;
LoggingSetup.loadHwiLogging = true;
LoggingSetup.multicoreEventCorrelation = false;
LoggingSetup.loggerType = LoggingSetup.LoggerType_STOPMODE;
LoggingSetup.sysbiosSwiLogging = false;
LoggingSetup.sysbiosHwiLogging = false;
LoggingSetup.sysbiosSemaphoreLogging = false;
LoggingSetup.loadLoggerSize = 1024;
LoggingSetup.sysbiosLoggerSize = 1024;
LoggingSetup.mainLoggerSize = 1024;
LoggingSetup.numCores = 8;

// -----------------------------------------------
//        Revision History
// -----------------------------------------------
// 23-May-2017 cnw: relocated cine heap declaration from HeapMemMgr.c to this file to resolve TI Compiler bug
//                  (issue id: SDSCM00043877)
// 09-May-2017 wlaw: Replace deprecated RTA by UIA.
//                   Remove unused variable, PlatformLib
//                   Remove Main logger buffer assignment because it is set to UIA logger buffer.
//                   Remove CPU Load module because it is automatically loaded in UIA.
// 11-Dec-2014 cnw: added QMSS for IPC & clean up
// 05-Jun-2014 wrz: cobbled together from our M2 .cfg file and some smaller mods for M2HF early development.


