--[[
  Copyright (c) 2021-2023 by Plexim GmbH
  All rights reserved.

  A free license is granted to anyone to use this software for any legal
  non safety-critical purpose, including commercial applications, provided
  that:
  1) IT IS NOT USED TO DIRECTLY OR INDIRECTLY COMPETE WITH PLEXIM, and
  2) THIS COPYRIGHT NOTICE IS PRESERVED in its entirety.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
--]]--
local T = require('targets.TI28')
local U = require('common.utils')
local P = require('resources.TI28P65x_pin_map')
local PLL = require('utils.pll_config')

local TripInputsAllocated = {}
local GpioAllocated = {}

function T.getFamilyPrefix()
  return '28P65x'
end

function T.getC2pConfig(c2pAdapter)
  return '28P650DK9_JTAG %s' % {c2pAdapter}
end

function T.getOptions()
  -- these are the values corresponding to drop down menu selections 
  -- in Coder Options. The order must match info.xml file.
  return {
    ChipCombo = {'28P650DK9'},
    boards = {'custom', 'launchpad', 'controlcard'},
    uniFlashConfigs = {
      launchpad = 'Launchpad_TMS320F28P650DK9.ccxml',
      controlcard = 'ControlCard_TMS320F28P650DK9.ccxml'
    },
    c2pConfigs = {
      launchpad = T.getC2pConfig('xds110'),
      controlcard = T.getC2pConfig('xds110'),
    },
    linkerFiles = {
      {'f28p65x_flash_lnk_cpu1.cmd', 'f28p65x_ram_lnk_cpu1.cmd'},
      {'f28p65x_flash_lnk_cpu2.cmd'},
    },
  }
end

function T.configure(resources)
  resources:add('ADC A')
  resources:add('ADC B')
  resources:add('ADC C')
  resources:add('ADCA-SOC', 0, 15)
  resources:add('ADCB-SOC', 0, 15)
  resources:add('ADCC-SOC', 0, 15)
  resources:add('Base Task Load')
  resources:add('Base Task Load CPU2')
  resources:add('CAN A')
  resources:add('CAP', 1, 7)
  resources:add('CMPSS', 1, 11)
  resources:add('CPU1TIMER', 0, 1)
  resources:add('CPU2TIMER', 0, 1)
  resources:add('DAC A')
  resources:add('DAC C')
  resources:add('EXTSYNC', 1, 2)
  resources:add('GPIO', 0, 242)
  resources:add('HRPWM', 1, 18)
  resources:add('IPC_FLAG', 4, 30)  -- only flags without interrupt capability, flag 31 used for start-up sync
  resources:add('MCAN A')
  resources:add('MCAN B')
  resources:add('Powerstage Control')
  resources:add('Powerstage Control CPU2')
  resources:add('PWM', 1, 18)
  resources:add('QEP', 1, 6)
  resources:add('SCI A')
  resources:add('SCI B')
  resources:add('SDFM 1', 1, 4) 
  resources:add('SDFM 2', 1, 4) 
  resources:add('SDFM 3', 1, 4) 
  resources:add('SDFM 4', 1, 4) 
  resources:add('SPI A')
  resources:add('SPI B')
  resources:add('SPI C')
  resources:add('SPI D')
  resources:add('UART A')
  resources:add('UART B')
  resources:add('XBAR_INPUT', 1, 16)
end

function T.validateAlternateFunction(fun)
  local settings = P.getPinSettings(fun)
  return settings ~= nil
end

function T.ts_getTargetParameters()
  local params = {
    adcs = {
      peripheralType = 4, 
      vrefConfigInterfaceType = 5,
      defaultVref = 3.0,
      num_channels = 16, 
      vref_min = 2.4,
      vref_max = 3.3, -- allowable range on external vref
      num_units = 3,  -- 3 ADCs (independent references not supported at this time)
      -- The below ADC channels require configuration as an analog port
      analog_mapping = {
        A6 = 209,
        A7 = 210,
        A8 = 211,
        A9 = 212,
        A10 = 213,
        A11 = 214,
        B4 = 215,
        B5 = 216,
        B6 = 207,
        B7 = 208,
        B8 = 217,
        B9 = 218,
        B10 = 219,
        C0 = 199,
        C1 = 200,
        C3 = 206,
        C4 = 205,
        C5 = 204,
        C6 = 203,
        C7 = 198,
        C8 = 202,
        C9 = 201,
      },
      vrefMap = {A = 'A', B = 'B', C = 'C'},
    },
    caps = {
      type = 3,
    },
    clas = {
      type = 2,
    },
    cbc_trip_inputs = {8, 9, 10, 11, 12},
    comps = {
      -- Comparator entries are stored as pin = {high = {unit, mux}, low = {unit, mux}}
      positive = {
        A0 = {high = {1, 1}, low = {1, 1}},
        A1 = {high = {1, 2}, low = {1, 2}},
        A2 = {high = {1, 0}, low = {1, 0}},
        A3 = {high = {1, 3}},
        A4 = {high = {2, 0}, low = {2, 0}},
        A5 = {high = {2, 3}, low = {9, 2}},
        A6 = {high = {7, 0}, low = {7, 0}},
        A7 = {high = {9, 2}, low = {4, 3}},
        A8 = {high = {8, 0}, low = {8, 0}},
        A9 = {low = {5, 3}},
        A10 = {high = {8, 1}, low = {8, 1}},
        A11 = {high = {8, 2}, low = {8, 2}},
        A14 = {high = {4, 0}, low = {4, 0}},
        A15 = {high = {4, 3}},
        B0 = {high = {3, 1}, low = {3, 1}},
        B1 = {high = {3, 2}, low = {3, 2}},
        B2 = {high = {3, 0}, low = {3, 0}},
        B3 = {low = {1, 3}},
        B4 = {high = {5, 1}, low = {5, 1}},
        B5 = {high = {5, 2}, low = {5, 2}},
        B6 = {high = {7, 1}, low = {7, 1}},
        B7 = {high = {7, 2}, low = {7, 2}},
        B8 = {high = {2, 1}, low = {2, 1}},
        B9 = {high = {2, 2}, low = {2, 2}},
        B10 = {high = {4, 1}, low = {4, 1}},
        B11 = {high = {4, 2}, low = {4, 2}},
        B13 = {high = {9, 0}, low = {9, 0}},
        C0 = {high = {6, 1}, low = {6, 1}},
        C1 = {high = {6, 2}, low = {6, 2}},
        C2 = {high = {6, 0}, low = {6, 0}},
        C3 = {low = {3, 3}},
        C4 = {high = {5, 0}, low = {5, 0}},
        C5 = {low = {2, 3}},
        C6 = {high = {10, 1}, low = {10, 1}},
        C7 = {high = {11, 1}, low = {11, 1}},
        C8 = {high = {10, 2}, low = {10, 2}},
        C9 = {high = {11, 2}, low = {11, 2}},
        C10 = {high = {10, 0}, low = {10, 0}},
        C11 = {high = {11, 0}, low = {11, 0}},
        C13 = {high = {9, 1}, low = {9, 1}},
      },
      b_supportsRampClkDivider = true,
      b_supportsRampDirection = true,
      b_supportsLowSideRamp = true,
    },
    cpu_timers = {0, 1},
    dacs = {
      type = 1,
      minOutputVoltage = 0.0,
      maxOutputVoltage = 3.3,
      -- Note this mapping is retained even though all references are the same because the
      -- getDacVref code requires a mapping for type 4 ADCs as well.
      -- DAC A use vrefA
      -- DAC C uses vrefB
      vrefMap = {A = 'A', C = 'B'},
    },
    dcans = {
      type = 1,
      ports = {'A'},
    },
    epwms = {
      type = 5, -- Note that we treat this target like an epwm_type4
      max_event_period = 15,
      num_units = 18,
      sync_group_size = 1,
    },
    gpios = {
      openDrainSupported = true,
    },
    hrpwms = {
      num_units = 18,
    },
    mcans = {
      type = 2,
      ports = {'A', 'B'},
    },
    qeps = {},
    scis = {
      type = 0,
      num_units = 2,
    },
    sdfms = {
      num_units = 4,
    },
    spis = {
      type = 2, fifo_depth = 16,
    },
    trip_groups = {A = 4, B = 5, C = 7},
    uarts = {
      num_units = 2,
    },
  }
  return params
end

function T.allocateGpio(gpio, properties, req, label)
  GpioAllocated[gpio] = properties
  req:add('GPIO', gpio, label)
end

function T.isGpioAllocated(gpio)
  return (GpioAllocated[gpio] ~= nil)
end

function T.getGpioProperties(gpio)
  return GpioAllocated[gpio]
end

function T.getNextAvailableTripInput()
  local availableInputs = T.getTargetParameters().cbc_trip_inputs
  for _, tin in ipairs(availableInputs) do
    if TripInputsAllocated[tin] == nil then
      TripInputsAllocated[tin] = true
      return tin
    end
  end
end

function T.getComparatorsForPin(pin)
  local compHigh, compLow

  local comp = T.getTargetParameters().comps.positive[pin]
  if comp == nil then
    return nil
  end
  if comp.high then
    compHigh = {
      unit = comp.high[1],
      mux = comp.high[2],
    }
  end
  if comp.low then
    compLow = {
      unit = comp.low[1],
      mux = comp.low[2],
    }
  end
  return {
    low = compLow,
    high = compHigh,
  }
end

function T.checkGpioIsValidPwmSync(gpio)
  -- NOTE: Chosen based on valid GPIOs that can be routed via XBAR
  if (not (((0 <= gpio) and (gpio <= 168)) or ((198 <= gpio) and (gpio <= 242)))) then
    U.error(
      'Only @param:Gpio: from 0-168 and 198-242 can be selected as external synchronization source for this target.')
  end
end

function T.pinHasAnalogMode(pin)
  -- With this chip some pins have optional analog mode and need special configuration because of it
  return ((198 <= pin) and (pin <= 219))
end

function T.getPwmSyncInSel(params)
  local mux
  if params.type == 'external' then
    if params.source_unit == 1 then
      mux = 0x18
    elseif params.source_unit == 2 then
      mux = 0x19
    else
      U.error('Unsupported external sync unit (%d).' % {params.source_unit})
    end
  elseif params.type == 'epwm' then
    -- PWMs 17 and 18 are offset from the rest of the options in the EPWMSYNCINSEL register table
    if (params.source_unit <= 16) then
      mux = params.source_unit
    else
      mux = params.source_unit + 11
    end
  else
    U.error('Unsupported sync type (%s).' % {params.type})
  end
  return mux
end

function T.getLowSpeedClock()
  return T.getCleanSysClkHz() / 4
end

-- PWM clock can run at full sysclk speed
function T.getPwmClock()
  -- Returns TBCLOCK = EPWMCLK/(CLKDIV*HSPCLKDIV) - EPWMCLK=SYSCLK, CLKDIV=/1, HSPCLKDIV=/1
  return T.getCleanSysClkHz()
end

function T.getTimerClock()
  -- relevant clock for dispatcher
  return T.getPwmClock()
end

function T.getDeadTimeClock()
  -- Same clock used (TBCLK) as PWM
  -- May change in the future if we allow for DBCTL[HALFCYCLE] to be set
  return T.getPwmClock()
end

function T.getAdcClock()
  -- Clock is set to be maximum of 50 MHz
  -- NOTE: data sheet specifies ADC clock can be up to 57 MHz, may want to change
  local sysClkHz = T.getCleanSysClkHz()
  if sysClkHz <= 50000000 then
    return sysClkHz
  elseif sysClkHz <= 75000000 then
    return sysClkHz / 1.5
  elseif sysClkHz <= 100000000 then
    return sysClkHz / 2
  elseif sysClkHz <= 120000000 then
    return sysClkHz / 2.5
  elseif sysClkHz <= 150000000 then
    return sysClkHz / 3.0
  elseif sysClkHz <= 175000000 then
    return sysClkHz / 3.5
  else
    return sysClkHz / 4
  end
end

function T.getCanClkAndMaxBrp()
  return T.getCleanSysClkHz(), 0x400
end

function T.calcACQPS(ts, sigmodeDifferential)
  local tsMin
  local acqpsMax = 511
  local acqpsMin = 0
  -- NOTE: This chip supports differential and single ended mode for both 12 bit and 16 bit.
  -- However, we are assuming 12 bit resolution for single ended and 16 bit for differential
  -- to match previous convention for type 4 ADCs.
  if sigmodeDifferential then
    tsMin = math.max(320e-9, 1 / T.getAdcClock()) -- per datasheet, differential (16 bit)
  else
    tsMin = math.max(75e-9, 1 / T.getAdcClock()) -- per datasheet, single ended (12 bit)
  end
  local sysClkHz = T.getCleanSysClkHz()
  if (not U.isScalar(ts)) or (ts < tsMin) then
    ts = tsMin
  end

  return U.clampNumber(math.ceil(ts * sysClkHz) - 1, {acqpsMin, acqpsMax})
end

function T.getCpuTimerSetupCode(unit, params)
  local code = [[
    CpuTimer%(unit)dRegs.TCR.bit.TSS = 1; // stop timer
    CpuTimer%(unit)dRegs.TPRH.all = 0;
    CpuTimer%(unit)dRegs.PRD.all = %(period)d - 1;
    CpuTimer%(unit)dRegs.TCR.bit.TRB = 1; // reload period
    CpuTimer%(unit)dRegs.TCR.bit.TIE = 1; // enable trigger to SOC/interrupt
  ]] % {
    unit = unit,
    period = params.period,
  }

  if params.isr then
    -- note, this is really hard-coded for CPUTimer0
    local isrConfigCode = [[
      PieCtrlRegs.PIEIER1.bit.INTx7 = 1;
      EALLOW;
      PieVectTable.TIMER%(unit)d_INT = &%(isr)s;
      EDIS;
      PieCtrlRegs.PIEIER1.bit.INTx7 = 1;
      PieCtrlRegs.PIEACK.all = PIEACK_GROUP1; // acknowledge interrupt to PIE
	  ]] % {
      unit = unit,
      isr = params.isr,
    }
    code = code..isrConfigCode
  end

  return code
end

function T.getEpwmTimersSyncCode()
  return [[
    CpuSysRegs.PCLKCR0.bit.GTBCLKSYNC = 1; // start all the timers synced
  ]]
end

function T.getAdcSetupCode(unitAsChar, params)
  local code = [[
    EALLOW;
    Adc%(adc)sRegs.ADCINTSEL1N2.bit.INT1CONT = 0; // disable ADCINT1 Continuous mode
    Adc%(adc)sRegs.ADCINTSEL1N2.bit.INT1SEL = %(int1sel)d; // setup EOC%(int1sel)d or OSINT(%(int1sel)d - 15) to trigger ADCINT1
    Adc%(adc)sRegs.ADCINTSEL1N2.bit.INT1E = 1; // enable ADCINT1
    Adc%(adc)sRegs.ADCCTL1.bit.INTPULSEPOS = 1; // ADCINT1 trips after AdcResults latch
    EDIS;
  ]] % {
    adc = string.lower(unitAsChar),
    int1sel = params.INT1SEL,
  }

  local zeroIndexedUnit = U.charToZeroIndexedInt(unitAsChar)
  if params.isr then
    local isrConfigCode = [[
      EALLOW;
      *(PINT *)((uint32_t)(&PieVectTable.ADCA1_INT) + ((uint32_t)%(unit)d)*sizeof(PINT *)) = &%(isr)s;
      PieCtrlRegs.PIEIER1.all |= %(pieBitMask)s;
      PieCtrlRegs.PIEACK.all = PIEACK_GROUP1;
      EDIS;
    ]] % {
      unit = zeroIndexedUnit,
      isr = params.isr,
      pieBitMask = (1 << zeroIndexedUnit),
    }

    code = code..isrConfigCode
  end

  return code
end

function T.getAdcInterruptAcknCode(unitAsChar, params)
  local code = [[
    Adc%sRegs.ADCINTFLGCLR.bit.ADCINT1 = 1; // clear ADCINT1 flag reinitialize for next SOC
    PieCtrlRegs.PIEACK.all = PIEACK_GROUP1; // acknowledge interrupt to PIE (All ADCS in group 1)
    IER |= M_INT1;
  ]] % {string.lower(unitAsChar)}

  return code
end

-- Configure Clock settings and limits related to the PLL
local function setAndGetPllLimits(useInternalOsc, isAuxClock)
  local limits = PLL.new(useInternalOsc)

  limits:set('INTERNAL_OSCILLATOR_HZ', {value = 10e6})  -- INTOSC2

  limits:set('OSCCLK', {min = 10e6, max = 20e6})
  limits:set('INTCLK', {min = 10e6, max = 25e6})
  limits:set('VCOCLK', {min = 220e6, max = 600e6})
  limits:set('PLLRAWCLK', {min = 6e6, max = 400e6})
  limits:set('SYSCLK', {min = 2e6, max = 200e6})

  limits:set('REFDIV', {max = 32})
  limits:set('ODIV', {max = 32})
  limits:set('IMULT', {max = 127})
  limits:set('SYSDIV', {max = 126})

  return limits:getLimits()  -- executes validation and returns limits
end

function T.getClockConfiguration()
  local useInternalOsc = (Target.Variables.useIntOsc == 1) -- convert gui value to boolean
  local limits = setAndGetPllLimits(useInternalOsc)

  local sysClkHz = T.getCleanSysClkHz()

  local inputClkHz
  if useInternalOsc then
    inputClkHz = limits.INTERNAL_OSCILLATOR_HZ.value
  else
    inputClkHz = T.getCleanExtClkHz()
  end

  -- establish PLL settings
  return {
    pllConfig = PLL.getClockConfiguration(limits, inputClkHz, sysClkHz),
    inputClkHz = inputClkHz,
    sysClkHz = sysClkHz,
    useInternalOsc = useInternalOsc,
  }
end

function T.getClockConfigurationCode(clockConfig)
  local pllConfig = clockConfig.pllConfig
  
  local clkSrcMacro
  if clockConfig.useInternalOsc then
    clkSrcMacro = 'SYSCTL_OSCSRC_OSC2'
  else
    clkSrcMacro = 'SYSCTL_OSCSRC_XTAL'
  end
  local dccBase = 0

  local cpuRate = 100.0 / clockConfig.sysClkHz * 10000000

  local declarations = [[
    void DevInit(uint32_t aDeviceClkConf);
    void InitFlashHz(Uint32 clkHz);
    void PieCntlInit(void);
    void F28x_usDelay(long LoopCount);

// Clock configuration
#define PLX_DEVICE_SETCLOCK_CFG       (%(clkSrcMacro)s | SYSCTL_IMULT(%(imult)d) | \
                                      SYSCTL_REFDIV(%(refdiv)d) | SYSCTL_ODIV(%(odiv)d) | \
                                      SYSCTL_SYSDIV(%(sysdiv)d) | SYSCTL_PLL_ENABLE | \
                                      SYSCTL_DCC_BASE_%(dccBase)d)

#define SYSCLK_HZ %(sysClkHz)dL
#define LSPCLK_HZ (%(sysClkHz)dL / 4l)

#define PLX_DELAY_US(A)  F28x_usDelay(((((long double) A * 1000.0L) / (long double)%(cpuRate)fL) - 9.0L) / 5.0L)
  ]] % {
    clkSrcMacro = clkSrcMacro,
    imult = pllConfig.imult,
    refdiv = pllConfig.refdiv,
    odiv = pllConfig.odiv,
    sysdiv = pllConfig.sysdiv,
    dccBase = dccBase,
    sysClkHz = clockConfig.sysClkHz,
    cpuRate = cpuRate,
  }

  local code = [[
    SysCtl_disableWatchdog();
    {
      uint32_t sysPllConfig = PLX_DEVICE_SETCLOCK_CFG;
      DevInit(sysPllConfig);

      SysCtl_setLowSpeedClock(SYSCTL_LSPCLK_PRESCALE_4);
    }

    InitFlashHz(SYSCLK_HZ);

    // set cpu timers to same clock as ePWM
    CpuTimer0Regs.TPR.all = 0;
    CpuTimer1Regs.TPR.all = 0;
    CpuTimer2Regs.TPR.all = 0;
    EALLOW;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER0 = 1;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER1 = 1;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER2 = 1;
    CpuSysRegs.PCLKCR0.bit.TBCLKSYNC = 0; // stop all the TB clocks
    CpuSysRegs.PCLKCR0.bit.GTBCLKSYNC = 0; // stop all the TB clocks
    ClkCfgRegs.PERCLKDIVSEL.bit.EPWMCLKDIV = 0;
    EDIS;
  ]]

  return {declarations = declarations, code = code}
end

-- FIX ME: Revisit CPU2 clock configuration after the dual core integration work.
local CONST = {
  -- System Clock Limits per datasheet
  PLL_SYS_CLK_MIN = 2e6,
  PLL_SYS_CLK_MAX = 200e6,
}

function T.getClockConfigurationCodeCpu2(clockConfig)
  local cpuRate = 100.0 / clockConfig.sysClkHz * 10000000

  local declarations = [[
    void DevInit();
    void InitFlashHz(Uint32 clkHz);
    void DSP28x_usDelay(long LoopCount);

// Clock configuration
#define SYSCLK_HZ %(sysClkHz)dL
#define LSPCLK_HZ (%(sysClkHz)d / 4l)
#define PLX_DELAY_US(A)  DSP28x_usDelay( \
        ((((long double) A * \
          1000.0L) / \
          %(cpuRate)fL) - 9.0L) / 5.0L)
  ]] % {
    sysClkHz = clockConfig.sysClkHz,
    cpuRate = cpuRate,
  }

  local code = [[
    DevInit();
    InitFlashHz(SYSCLK_HZ);
    // set cpu timers to same clock as ePWM
    CpuTimer0Regs.TPR.all = 0;
    CpuTimer1Regs.TPR.all = 0;
    CpuTimer2Regs.TPR.all = 0;
    EALLOW;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER0 = 1;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER1 = 1;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER2 = 1;
    CpuSysRegs.PCLKCR0.bit.TBCLKSYNC = 0; // stop all the TB clocks
    ClkCfgRegs.PERCLKDIVSEL.bit.EPWMCLKDIV = 0;
    EDIS;
  ]]

  return {declarations = declarations, code = code}
end

function T.getCpu2BootCode()
  local includes = {'memcfg.h'}

  local declarations = [[
#define BOOTMODE_BOOT_TO_FLASH_BANK3_SECTOR0         0x83U
#define BOOT_KEY                                0x5A000000UL

    static void BootCPU2ToFlashSector3()
    {
      // Put CPU2 into reset
      SysCtl_controlCPU2Reset(SYSCTL_CORE_ACTIVE);

      // Set boot mode for CPU2 (run in flash sector 3)
      IPC_setBootMode(IPC_CPU1_L_CPU2_R,
                      (BOOT_KEY | BOOTMODE_BOOT_TO_FLASH_BANK3_SECTOR0));

      // Set IPC flag 0
      IPC_setFlagLtoR(IPC_CPU1_L_CPU2_R, IPC_FLAG0);

      // Bring CPU2 out of reset
      SysCtl_controlCPU2Reset(SYSCTL_CORE_DEACTIVE);
      while(SysCtl_isCPU2Reset() == 0x1U);
    }
  ]]

  local code = [[
    MemCfg_setGSRAMControllerSel(MEMCFG_SECT_GS0 | MEMCFG_SECT_GS1 | MEMCFG_SECT_GS2, MEMCFG_GSRAMCONTROLLER_CPU2);
    SysCtl_allocateDxRAM(SYSCTL_D4RAM, SYSCTL_CPUSEL_CPU2);
    SysCtl_allocateDxRAM(SYSCTL_D5RAM, SYSCTL_CPUSEL_CPU2);
    SysCtl_allocateFlashBank(SYSCTL_FLASH_BANK3, SYSCTL_CPUSEL_CPU2);
    SysCtl_allocateFlashBank(SYSCTL_FLASH_BANK4, SYSCTL_CPUSEL_CPU2);

    BootCPU2ToFlashSector3();

    // wait for CPU2 to signal that has completed its initialization
    while(!(HWREG(IPC_CPUXTOCPUX_BASE + IPC_O_CPU2TOCPU1IPCSTS) & IPC_FLAG31)){
        continue;
    }

    // acknowledge flag which will allow CPU2 to proceed
    HWREG(IPC_CPUXTOCPUX_BASE + IPC_O_CPU1TOCPU2IPCACK) = IPC_FLAG31;
  ]]

  return {declarations = declarations, code = code, includes = includes}
end

function T.getCpu2BootCodeCpu2()
  local code = [[
    // signal to CPU1 that we are configured
    HWREG(IPC_CPUXTOCPUX_BASE + IPC_O_CPU1TOCPU2IPCSET) = IPC_FLAG31;
    // wait for acknowledgment and permission to go
    while(HWREG(IPC_CPUXTOCPUX_BASE + IPC_O_CPU1TOCPU2IPCFLG) & IPC_FLAG31){
        continue;
    }
  ]]

  return {declarations = nil, code = code}
end

T.ts_epwm = require('peripherals.epwm_type4').getFunctions(T)

return T
