/** @file
  Interrupt Assign

 @copyright
  INTEL CONFIDENTIAL
  Copyright 2016 -2017 Intel Corporation.

  The source code contained or described herein and all documents related to the
  source code ("Material") are owned by Intel Corporation or its suppliers or
  licensors. Title to the Material remains with Intel Corporation or its suppliers
  and licensors. The Material may contain trade secrets and proprietary and
  confidential information of Intel Corporation and its suppliers and licensors,
  and is protected by worldwide copyright and trade secret laws and treaty
  provisions. No part of the Material may be used, copied, reproduced, modified,
  published, uploaded, posted, transmitted, distributed, or disclosed in any way
  without Intel's prior express written permission.

  No license under any patent, copyright, trade secret or other intellectual
  property right is granted to or conferred upon you by disclosure or delivery
  of the Materials, either expressly, by implication, inducement, estoppel or
  otherwise. Any license under such intellectual property rights must be
  express and approved by Intel in writing.

  Unless otherwise agreed by Intel in writing, you may not remove or alter
  this notice or any other notice embedded in Materials by Intel or
  Intel's suppliers or licensors in any way.

  This file contains an 'Intel Peripheral Driver' and is uniquely identified as
  "Intel Reference Module" and is licensed for Intel CPUs and chipsets under
  the terms of your license agreement with Intel or your vendor. This file may
  be modified by the user, subject to additional terms of the license agreement.

@par Specification Reference:
**/

#include "ScInitPei.h"

/**
  Configures interrupt pin assignment for standard PCI device

  @param[in] Device          Device number
  @param[in] Function        Function number
  @param[in] InterruptPin    INTx

  @retval Status
**/
EFI_STATUS
StandardIntSet (
  IN UINT8   Device,
  IN UINT8   Function,
  IN UINT8   InterruptPin
  )
{
  UINTN     Address;

  Address = MmPciBase (DEFAULT_PCI_BUS_NUMBER_SC, Device, Function);

  MmioWrite8 (Address + PCI_INT_PIN_OFFSET, InterruptPin);

  return EFI_SUCCESS;
}

/**
  Configures PCI Express Port interrupt pin assignment

  @param[in] Device          Device number
  @param[in] Function        Function number
  @param[in] InterruptPin    INTx

  @retval Status
**/
EFI_STATUS
PciExpressIntSet (
  IN UINT8   Device,
  IN UINT8   Function,
  IN UINT8   InterruptPin
  )
{
  UINTN     Address;
  UINT32    Data32Or;
  UINT32    Data32And;

  //
  // Set Interrupt Pin
  //
  Address = MmPciBase (DEFAULT_PCI_BUS_NUMBER_SC, Device, Function) + R_SC_PCH_PCIE_CFG_STRPFUSECFG;
  Data32And = (UINT32)~B_SC_PCH_PCIE_CFG_STRPFUSECFG_PXIP;
  Data32Or = (UINT32)(InterruptPin) << N_SC_PCH_PCIE_CFG_STRPFUSECFG_PXIP;
  MmioAndThenOr32 (Address, Data32And, Data32Or);
  return EFI_SUCCESS;
}

/**
  Configures SC devices interrupts

  @param[in] SchPolicy                  The SC Policy PPI instance

  @retval EFI_SUCCESS                   Succeeds.
**/
EFI_STATUS
ScConfigureInterrupts (
  IN  SC_POLICY_PPI *ScPolicyPpi
  )
{
  EFI_STATUS           Status;
  SC_INTERRUPT_CONFIG  *InterruptConfig;
  UINTN                P2sbPciMmBase = 0;
  UINTN                XhciPciMmBase = 0;
  UINT32               Index = 0;
  UINT32               Data = 0;
  UINT8                Buffer[8]={0};
  UINTN                BufferSize=1;
  //
  // General Interrupt Requirements for BXT South Cluster Devices
  //
  // 1.) Define device sideband endpoint port, PCICFGCTRL reg offset,
  //     and IRQ and interrupt pin in directIrqTable.
  //
  // 2.) Set device IRQ in PciTree.asl (IntPin should match the value in directIrqTable).
  //
  // 3.) Set IRQ polarity and ensure value is correct in ITSS.IPC0, ITSS.IPC1, etc.
  //     register programming below.
  //
  // 4.) Add BDF with IRQ for the device in IrqInitTable in ScInit.c.
  //     This value is written to the interrupt line register (offset 0x3C) in the device's
  //     PCI CFG space.
  //
  // 5.) Write the Master Message Enable bit of ITSS to enable the interrupt transaction
  //     to IOSF
  //
  // Note: MSIs are set by OS device drivers and typically require no IAFW configuration.
  //

  DEBUG ((DEBUG_INFO, "ScConfigureInterrupts() - Start\n"));
  Status = GetConfigBlock ((VOID *) ScPolicyPpi, &gInterruptConfigGuid, (VOID *) &InterruptConfig);
  ASSERT_EFI_ERROR (Status);

  //
  // Loop through whole interrupt table and program devices registers
  //
  for (Index = 0; Index < InterruptConfig->NumOfDevIntConfig; Index++) {
    //
    // Do not configure devices with Dxx < 16
    //
    if (InterruptConfig->DevIntConfig[Index].Device < 16) {
      continue;
    }

    switch (InterruptConfig->DevIntConfig[Index].Device) {
      case PCI_DEVICE_NUMBER_SC_PCIE_DEVICE_1:
      case PCI_DEVICE_NUMBER_SC_PCIE_DEVICE_2:
        //
        // PCI Express Port
        //
        PciExpressIntSet (
          InterruptConfig->DevIntConfig[Index].Device,
          InterruptConfig->DevIntConfig[Index].Function,
          InterruptConfig->DevIntConfig[Index].IntX
          );
        break;
      default:
        //
        //Standard PCI Devices which have Interrupt Pin register under PciCfgSpace + 3Dh
        //
        StandardIntSet (
          InterruptConfig->DevIntConfig[Index].Device,
          InterruptConfig->DevIntConfig[Index].Function,
          InterruptConfig->DevIntConfig[Index].IntX
          );
        break;
    }
  }
  P2sbPciMmBase = MmPciBase (DEFAULT_PCI_BUS_NUMBER_SC, PCI_DEVICE_NUMBER_P2SB, PCI_FUNCTION_NUMBER_P2SB);

  XhciPciMmBase = MmPciBase (DEFAULT_PCI_BUS_NUMBER_SC, PCI_DEVICE_NUMBER_XHCI, PCI_FUNCTION_NUMBER_XHCI);
  //
  // Writing the Master Message Enable (bit 0) of ITSS Register 0x3334
  //
  SideBandAndThenOr32 (SB_ITSS_PORT, R_SC_ITSS_PCR_MMC, 0xFFFFFFFF, BIT0);

  //
  // Ensure HPET and IOAPIC are enabled in P2SB PCI CFG space
  // 1) HPET   -> Register 0x60 bit 7
  // 2) IOAPIC -> Register 0x64 bit 8
  //
  MmioOr16((UINTN)MmioAddress(P2sbPciMmBase, R_SC_PCH_P2SB_CFG_HPTC), (UINT16)(B_SC_PCH_P2SB_CFG_HPTC_AE));
  MmioOr16((UINTN)MmioAddress(P2sbPciMmBase, R_SC_PCH_P2SB_CFG_IOAC), (UINT16)(B_SC_PCH_P2SB_CFG_IOAC_AE));

  // Set Max Writes Pending (Max Number of Writes Allowed on IOSF-SB to SBREG_BAR)
  MmioWrite32((UINTN)MmioAddress(P2sbPciMmBase, R_SC_P2SB_CFG_P2SBC), (UINT32)0x07);

  // Set MemSpaceEn and BusInitiate in P2SB Command Register
  MmioWrite32 ((UINTN)MmioAddress (P2sbPciMmBase, PCI_COMMAND_OFFSET), (UINT32)EFI_PCI_COMMAND_MEMORY_SPACE | EFI_PCI_COMMAND_BUS_MASTER);

  //
  // Set PCICFGCTRL register in corresponding SB port for each device in directIrqTable
  //
  for (Index = 0; Index < InterruptConfig->NumOfDirectIrqTable; Index++) {
    SideBandWrite32 (
      InterruptConfig->DirectIrqTable[Index].Port,
      InterruptConfig->DirectIrqTable[Index].PciCfgOffset,
      (InterruptConfig->DirectIrqTable[Index].PciIrqNumber << N_PCICFGCTRL_PCI_IRQ) +
      (InterruptConfig->DirectIrqTable[Index].IrqPin << N_PCICFGCTRL_INT_PIN)
      );
  }

  //
  // Set xHCI Interrupt Pin
  // Inaccessible after XHCC1.ACCTRL is set (lock down bit)
  //
  MmioWrite8((UINTN)(XhciPciMmBase + R_SC_XHCI_CFG_INT_PN), (UINT8)V_SC_XHCI_CFG_INT_PN);

  //
  // Set ACPIIN / ACPIIE For HD Audio Device
  //
  DEBUG((EFI_D_INFO, "Set ACPIIN / ACPIIE For HD Audio Device.\n"));
  SideBandAndThenOr32 (
    SB_AUDIO_PORT,
    R_SC_HDA_PCR_PCICFGCTL,
    0xFFFFFFFF,
	(UINT32)((V_SC_HDA_CFG_INTLN << 8) | B_SC_HDA_PCR_PCICFGCTL_SPCBAD | B_SC_HDA_PCR_PCICFGCTL_ACPIIE)
    );

  //
  // Program Legacy Interrupt Routing Registers
  // ITSS private registers are only accessible via DWORD aligned IOSF-SB CrWr messages
  //
  Data = 
    (((InterruptConfig->PxRcRouting[0]) << 0) +  // R_SC_ITSS_PCR_PARC    PIRQA->IRQx Routing Control
    ((InterruptConfig->PxRcRouting[1]) << 8) +   // R_SC_ITSS_PCR_PBRC    PIRQB->IRQx Routing Control
    ((InterruptConfig->PxRcRouting[2]) << 16) +  // R_SC_ITSS_PCR_PCRC    PIRQC->IRQx Routing Control
    ((InterruptConfig->PxRcRouting[3]) << 24));  // R_SC_ITSS_PCR_PDRC    PIRQD->IRQx Routing Control
  SideBandWrite32 (SB_ITSS_PORT, R_SC_ITSS_PCR_PARC, Data);
  
  Data = 
    (((InterruptConfig->PxRcRouting[4]) << 0) +  // R_SC_ITSS_PCR_PERC    PIRQE->IRQx Routing Control
    ((InterruptConfig->PxRcRouting[5]) << 8) +   // R_SC_ITSS_PCR_PFRC    PIRQF->IRQx Routing Control
    ((InterruptConfig->PxRcRouting[6]) << 16) +  // R_SC_ITSS_PCR_PGRC    PIRQG->IRQx Routing Control
    ((InterruptConfig->PxRcRouting[7]) << 24));  // R_SC_ITSS_PCR_PHRC    PIRQH->IRQx Routing Control   
  SideBandWrite32 (SB_ITSS_PORT, R_SC_ITSS_PCR_PERC, Data);

  
  Data =
    (((V_SC_ITSS_PCR_IAR_PIRQA | V_SC_ITSS_PCR_IBR_PIRQA | V_SC_ITSS_PCR_ICR_PIRQA | V_SC_ITSS_PCR_IDR_PIRQA) << 0) +  //  R_SC_ITSS_PCR_PIR0 Pin->PIRQx Routing for NPK
	((V_SC_ITSS_PCR_IAR_PIRQH | V_SC_ITSS_PCR_IBR_PIRQH | V_SC_ITSS_PCR_ICR_PIRQH | V_SC_ITSS_PCR_IDR_PIRQH) << 16))   //  R_SC_ITSS_PCR_PIR1 Pin->PIRQx Routing for GMM
    ;
  SideBandWrite32 (SB_ITSS_PORT, R_SC_ITSS_PCR_PIR0, Data);

  Data =
    (((V_SC_ITSS_PCR_IAR_PIRQD | V_SC_ITSS_PCR_IBR_PIRQD | V_SC_ITSS_PCR_ICR_PIRQD | V_SC_ITSS_PCR_IDR_PIRQD) << 0) +  //  R_SC_ITSS_PCR_PIR2 Pin->PIRQx Routing for Display
	((V_SC_ITSS_PCR_IAR_PIRQG | V_SC_ITSS_PCR_IBR_PIRQH | V_SC_ITSS_PCR_ICR_PIRQE | V_SC_ITSS_PCR_IDR_PIRQF) << 16))   //  R_SC_ITSS_PCR_PIR3 Pin->PIRQx Routing for PCIE Device 20
    ;
  SideBandWrite32 (SB_ITSS_PORT, R_SC_ITSS_PCR_PIR2, Data);

  Data =
    (((V_SC_ITSS_PCR_IAR_PIRQA | V_SC_ITSS_PCR_IBR_PIRQA | V_SC_ITSS_PCR_ICR_PIRQA | V_SC_ITSS_PCR_IDR_PIRQA) << 0) +  //  R_SC_ITSS_PCR_PIR4 Pin->PIRQx Routing for Audio
	((V_SC_ITSS_PCR_IAR_PIRQE | V_SC_ITSS_PCR_IBR_PIRQE | V_SC_ITSS_PCR_ICR_PIRQE | V_SC_ITSS_PCR_IDR_PIRQE) << 16))   //  R_SC_ITSS_PCR_PIR5 Pin->PIRQx Routing for CSE
    ;
  SideBandWrite32 (SB_ITSS_PORT, R_SC_ITSS_PCR_PIR4, Data);

  Data =
    // Adjust PCI Interrupt Routing configuration of PCIe in ITSS PIR6 & ACPI _PRT for PCI Express Graphic Card
	(((V_SC_ITSS_PCR_IAR_PIRQG | V_SC_ITSS_PCR_IBR_PIRQH | V_SC_ITSS_PCR_ICR_PIRQE | V_SC_ITSS_PCR_IDR_PIRQF) << 0) +  //  R_SC_ITSS_PCR_PIR6 Pin->PIRQx Routing for PCIE Device 19
	((V_SC_ITSS_PCR_IAR_PIRQB | V_SC_ITSS_PCR_IBR_PIRQB | V_SC_ITSS_PCR_ICR_PIRQB | V_SC_ITSS_PCR_IDR_PIRQB) << 16))   //  R_SC_ITSS_PCR_PIR7 Pin->PIRQx Routing for xHCI
    ;
  SideBandWrite32 (SB_ITSS_PORT, R_SC_ITSS_PCR_PIR6, Data);

  Data =
    (((V_SC_ITSS_PCR_IAR_PIRQC | V_SC_ITSS_PCR_IBR_PIRQC | V_SC_ITSS_PCR_ICR_PIRQC | V_SC_ITSS_PCR_IDR_PIRQC) << 0) +  //  R_SC_ITSS_SB_PIR8 Pin->PIRQx Routing for xDCI
    ((V_SC_ITSS_PCR_IAR_PIRQD | V_SC_ITSS_PCR_IBR_PIRQD | V_SC_ITSS_PCR_ICR_PIRQD | V_SC_ITSS_PCR_IDR_PIRQD) << 16))   //  R_SC_ITSS_SB_PIR9 Pin->PIRQx Routing for SATA
    ;
  SideBandWrite32 (SB_ITSS_PORT, R_SC_ITSS_PCR_PIR8, Data);

  Data =
    (((V_SC_ITSS_PCR_IAR_PIRQE | V_SC_ITSS_PCR_IBR_PIRQE | V_SC_ITSS_PCR_ICR_PIRQE | V_SC_ITSS_PCR_IDR_PIRQE) << 0) +  //  R_SC_ITSS_SB_PIR10 Pin->PIRQx Routing for SMBus
    (0))                                                                                               //  R_SC_ITSS_SB_PIR11 Pin->PIRQx Routing Reserved
    ;
  SideBandWrite32 (SB_ITSS_PORT, R_SC_ITSS_PCR_PIR10, Data);

  //
  // Set IRQ Interrupt Polarity Control
  //
  for (Index = 0; Index < SC_NUM_IPC_REG; Index++) {
    SideBandWrite32 (SB_ITSS_PORT, (UINT16) (R_SC_ITSS_PCR_IPC0 + 4 * Index), InterruptConfig->IPC[Index]);
  }

  Data = (UINT32) B_SC_ITSS_PCR_MSGDC_IRQDDEN;
  SideBandWrite32 (SB_ITSS_PORT, R_SC_ITSS_PCR_MSGDC, Data);

  // Joint PMC FW + BIOS WA.PMC FW to add setting miscseccfg.sbtrigdis on Sx entry (set to '1), 
  // and add IPC1 trusted tunnel message entry which allows BIOS to write to miscseccfg (SBTRIGDIS field ONLY) when SAI_BOOT_BIOS.
  // BIOS to use the IPC1 to clear sbtrigdis after the restore of ITSS, while SAI_BOOT_BIOS
  //
  BufferSize=1;
  Data = (UINT32)IPC_GPIO_SCC_MISCSECCFG;
  Status = IpcSendCommandEx (IPC_CMD_ID_TRUSTED_SIDEBAND_TUNNEL, IPC_SUBCMD_ID_TRUSTED_SIDEBAND_TUNNEL_READ, &Data, BufferSize);
  if (!EFI_ERROR(Status)) {
	Data &= ~(UINT32)B_GPIO_MISCSECCFG_SBTRIGDIS;
	Buffer[0]=IPC_GPIO_SCC_MISCSECCFG;
	Buffer[4]=(UINT8)(Data & 0xFF);
	Buffer[5]=(UINT8)((Data>>8) & 0xFF);
	Buffer[6]=(UINT8)((Data>>16) & 0xFF);
	Buffer[7]=(UINT8)((Data>>24) & 0xFF);
	BufferSize = 8;
	Status = IpcSendCommandEx (IPC_CMD_ID_TRUSTED_SIDEBAND_TUNNEL, IPC_SUBCMD_ID_TRUSTED_SIDEBAND_TUNNEL_WRITE, &Buffer, BufferSize);
	if (EFI_ERROR(Status)) {
      DEBUG ((DEBUG_ERROR, "IpcCommand Write Failure, Status: 0x%x\n",Status));
	}
  } else {
    DEBUG ((DEBUG_ERROR, "Error Sending IpcCommand, Status: %r\n", Status));
  }
  
  DEBUG ((DEBUG_INFO, "ScConfigureInterrupts() - End\n"));
  return EFI_SUCCESS;
}


