text:
//==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc.  All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file AMDTPowerProfileControl.cpp
///
//==================================================================================

#if ( defined (_WIN32) || defined (_WIN64) )
    #include <windows.h>
    #include <AMDTDriverControl/inc/DriverControl.h>
#endif

#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <ppCountersStringConstants.h>
#include <AMDTRawDataFileHeader.h>
#include <PowerProfileHelper.h>
#include <PowerProfileDriverInterface.h>
#include <AMDTPowerProfileControl.h>
#include <AMDTPowerProfileInternal.h>
#include <AMDTPowerProfileDataTypes.h>
#include <AMDTSmu8Interface.h>
#include <SupportedDeviceList.h>
#include <OsFileWrapper.h>

#define SMU_RETRY_COUNT_MAX       1024
#define SMU_LOG_MSG_RETRY_MAX       32
#define DEVICE_TRACE_STR "Device:B%d/D%d/F%d dev-id:0x%x, hw-type:%d, dev-type:%d, model:%s, sname:%s, ip-ver: %d, access:%d"
// This macro needs to be removed in release branch
#define CONTROL_POOL_SIZE 1048576 // 1MB

// Globals
extern AMDTUInt8* g_pSharedBuffer;
extern bool g_internalCounters;
extern bool g_isSVI2Supported;

PwrInternalAddr g_internalCounterAddr;
// Create control layer pool.
static MemoryPool g_controlMemoryPool;
wchar_t g_rawFileName[MAX_PATH_LEN];
static bool g_isOnline = false;
static bool g_isSvi2Selected = false;

AMDTPwrProfilingState g_powerProfileState = PowerProfilingUnavailable;
static AMDTPwrTargetSystemInfo* g_pTargetSystemInfo = NULL;

PciDeviceInfo g_activePciDevice[PLATFORM_SMU_CNT + 2];
PciPortAddress  g_activePciPortList[PLATFORM_SMU_CNT + 2 ];

static AMDTPwrApuPstateList g_pStateInfo;

bool GetAvailableSmuList(SmuList* pList);

// Basic Counters- Sample id, record-id, timestamp
AMDTPwrAttributeTypeInfo g_basicCounters[] =
{
#include "BasicCounterList.h"
};

// Node specific Counters- PID, TID, pstate, cef, node temperature
AMDTPwrAttributeTypeInfo g_nodeCounters[] =
{
#include "NodeCounterList.h"
};

// Smu7.0- Kaveri
AMDTPwrAttributeTypeInfo g_smu7Counters[] =
{
#include "Smu7CounterList.h"
};

// Smu7.5 -Mullins
AMDTPwrAttributeTypeInfo g_smu75Counters[] =
{
#include "Smu75CounterList.h"
};

// Smu8 - Carrizo
AMDTPwrAttributeTypeInfo g_smu8Counters[] =
{
#include "Smu8CounterList.h"
};

AMDTPwrAttributeTypeInfo g_CounterDgpuSmu7_0[] =
{
#include "Smu7DgpuCounterList.h"
};

/** \typedef ProfileControlHandle
    \brief A handle to identify which profiles were opened for driver work.
    \ingroup datafiles

    The handle is necessary for all functions related to retrieving data from
    the opened profiles.
*/
typedef void* ProfileControlHandle;

//AMDTPwrProfileInitialize-This will set up the power profiling driver for your profile .
AMDTResult PwrProfileInitialize(
    AMDTPwrProfileInitParam* pParam)
{
    AMDTInt32 ret = AMDT_STATUS_OK;

    if (!pParam)
    {
        ret = AMDT_ERROR_FAIL;
        PwrTrace("PwrProfileInitialize failed as pParam == NULL");
    }

    g_isOnline = (bool)pParam->isOnline;

    if (AMDT_STATUS_OK == ret)
    {
        //Driver initialization
        ret = OpenPowerProfileDriver();
    }

    if (AMDT_STATUS_OK == ret)
    {
        // Create memory pool for API layer
        ret = CreateMemoryPool(&g_controlMemoryPool, CONTROL_POOL_SIZE);
    }

    if (AMDT_STATUS_OK == ret)
    {
        g_powerProfileState = PowerProfilingInitialized;
        memset(&g_attributeList, 0, sizeof(AMDTPwrProfileAttributeList));
        g_attributeList.pAttrList = (AMDTPwrAttributeTypeInfo*) GetMemoryPoolBuffer(&g_controlMemoryPool, COUNTERID_MAX_CNT * sizeof(AMDTPwrAttributeTypeInfo));

        if (NULL == g_attributeList.pAttrList)
        {
            ret = AMDT_ERROR_OUTOFMEMORY;
        }
    }

    // Initialize p state structure
    g_pStateInfo.m_cnt = 0;

    return ret;
}

// PwrProfileUnregisterClient: Unregister client from driver's client list
// Release all internel memory allocated by driver and state the state
// machine to PowerProfilingUnavailable.
AMDTResult PwrProfileUnregisterClient()
{
    AMDTInt32 ret = AMDT_STATUS_OK;
    AMDTUInt32 res = 0;
    AMDTUInt32 clientId = 0;

    //Check if profiler is not event initialized
    if (g_powerProfileState == PowerProfilingUnavailable)
    {
        ret = AMDT_ERROR_ACCESSDENIED;
    }

    if ((g_powerProfileState == PowerProfiling) ||
        (g_powerProfileState == PowerProfilingPaused))
    {
        ret = AMDT_STATUS_PENDING;
    }

    if (AMDT_STATUS_OK == ret)
    {
        ret = GetPowerDriverClientId(&clientId);
    }

    if (AMDT_STATUS_OK == ret)
    {
        //unregister driver
        ret = CommandPowerDriver(DRV_CMD_TYPE_IN,
                                 IOCTL_UNREGISTER_CLIENT,
                                 &clientId,
                                 sizeof(AMDTUInt32),
                                 0,
                                 0,
                                 &res);
    }

    // Set The profiling state to uninitialised
    g_powerProfileState = PowerProfilingStopped;

    if (AMDT_STATUS_OK != ret)
    {
        PwrTrace("PwrProfileUnregisterClient failed:");
    }

    return ret;
}

// PwrProfileClose: Close the power profiler seession.
// Cleanup all memory allocated by backend
AMDTResult PwrProfileClose()
{
    AMDTResult ret = AMDT_STATUS_OK;

    // Check the status of the power profiling
    if (PowerProfiling == g_powerProfileState)
    {
        PwrStopProfiling();
    }

    g_powerProfileState = PowerProfilingUnavailable;

    // Release the memory pool buffer
    ret = ReleaseMemoryPool(&g_controlMemoryPool);

    // Relase g_pTargetSystemInfo memory
    if (NULL != g_pTargetSystemInfo)
    {
        free(g_pTargetSystemInfo);
        g_pTargetSystemInfo = NULL;
    }

    return ret;
}

// PwrGetSupportedAttributeList: This function prepares the list of supported counters
// including APU and dGPU which are connected to the platform
// This function needs to be modified whenever there is a new addion of SMU version
// for APU and dGPU
AMDTResult PwrGetSupportedAttributeList(
    /*out*/AMDTPwrProfileAttributeList* pList)

{
    AMDTResult ret = AMDT_STATUS_OK;
    AMDTUInt32 size = 0;
    AMDTPwrTargetSystemInfo sysInfo;
    AMDTUInt32 smuCnt = 0;
    AMDTUInt32 counterCnt = 0;

    if (0 == g_attributeList.attrCnt)
    {
        // Get base counter list
        memcpy(g_attributeList.pAttrList, &g_basicCounters[0], sizeof(g_basicCounters));
        counterCnt = sizeof(g_basicCounters) / sizeof(AMDTPwrAttributeTypeInfo);
        g_attributeList.attrCnt = counterCnt;

        ret = AMDTPwrGetTargetSystemInfo(&sysInfo);

        if ((AMDT_STATUS_OK == ret) && (true == sysInfo.m_isPlatformSupported))
        {

            if ((true == sysInfo.m_isAmdApu) && (nullptr != sysInfo.m_pNodeInfo))
            {
                if (SMU_IPVERSION_7_0 == sysInfo.m_pNodeInfo->m_smuIpVersion)

                {
                    memcpy(g_attributeList.pAttrList + g_attributeList.attrCnt,
                           &g_smu7Counters[0],
                           sizeof(g_smu7Counters));

                    counterCnt = sizeof(g_smu7Counters) / sizeof(AMDTPwrAttributeTypeInfo);
                    g_attributeList.attrCnt += counterCnt;
                }
                else if (SMU_IPVERSION_7_5 == sysInfo.m_pNodeInfo->m_smuIpVersion)
                {
                    memcpy(g_attributeList.pAttrList + g_attributeList.attrCnt,
                           &g_smu75Counters[0],
                           sizeof(g_smu75Counters));

                    counterCnt = sizeof(g_smu75Counters) / sizeof(AMDTPwrAttributeTypeInfo);
                    g_attributeList.attrCnt += counterCnt;
                }
                else if ((SMU_IPVERSION_8_0 == sysInfo.m_pNodeInfo->m_smuIpVersion)
                         || (SMU_IPVERSION_8_1 == sysInfo.m_pNodeInfo->m_smuIpVersion))
                {
                    memcpy(g_attributeList.pAttrList + g_attributeList.attrCnt,
                           &g_smu8Counters[0],
                           sizeof(g_smu8Counters));

                    counterCnt = sizeof(g_smu8Counters) / sizeof(AMDTPwrAttributeTypeInfo);
                    g_attributeList.attrCnt += counterCnt;
                }
            }

            // Add AMD node counters like pstate,PID,TID, node temperature
            memcpy(g_attributeList.pAttrList + g_attributeList.attrCnt,
                   &g_nodeCounters[0],
                   sizeof(g_nodeCounters));

            counterCnt = sizeof(g_nodeCounters) / sizeof(AMDTPwrAttributeTypeInfo);
            g_attributeList.attrCnt += counterCnt;
        }

        for (smuCnt = 0; smuCnt < sysInfo.m_smuTable.m_count; smuCnt++)
        {
            AMDTUInt32 id = 0;
            AMDTPwrAttributeTypeInfo* attrInfo = NULL;
            SmuInfo* smuInfo = &sysInfo.m_smuTable.m_info[smuCnt];

            if (APU_SMU_ID == smuInfo->m_packageId)
            {
                continue;
            }

            if ((SMU_IPVERSION_7_0 == smuInfo->m_smuIpVersion)
                || (SMU_IPVERSION_7_1 == smuInfo->m_smuIpVersion)
                || (SMU_IPVERSION_7_2 == smuInfo->m_smuIpVersion))
            {
                size = sizeof(g_CounterDgpuSmu7_0);
                attrInfo = g_attributeList.pAttrList + g_attributeList.attrCnt;
                memcpy(attrInfo, &g_CounterDgpuSmu7_0[0], size);
                g_attributeList.attrCnt += (size / sizeof(AMDTPwrAttributeTypeInfo));

                for (id = 0; id < (size / sizeof(AMDTPwrAttributeTypeInfo)); id++)
                {
                    attrInfo[id].m_attrId = attrInfo[id].m_attrId
                                            + DGPU_COUNTER_BASE_ID
                                            + (smuInfo->m_packageId - APU_SMU_ID - 1)
                                            * DGPU_COUNTERS_MAX;
                }
            }
        }
    }

    pList->pAttrList = g_attributeList.pAttrList;
    pList->attrCnt = g_attributeList.attrCnt;
    return ret;
}

// SetAttributeMask: Prepare and set counter mask for each accessible components
// Line smu, Pcie, MSR access
AMDTResult SetAttributeMask(AMDTUInt16* clientAttrList , AMDTUInt32 attrCnt, ProfileConfig* cfg)
{
    AMDTInt32 ret = AMDT_STATUS_OK;
    AMDTUInt32 cnt = 0;
    g_isSvi2Selected = false;
    AMDTUInt64* pMask = nullptr;

    if (!clientAttrList)
    {
        ret = AMDT_ERROR_INVALIDARG;
        PwrTrace("clientAttrList == NULL");
    }

    pMask = &cfg->m_apuCounterMask;

    if (AMDT_STATUS_OK == ret)
    {
        AMDTPwrProfileAttributeList supportedList;

        //Get the actual id from supported list
        PwrGetSupportedAttributeList(&supportedList);

        for (cnt = 0; cnt < cfg->m_activeList.m_count; cnt++)
        {
            cfg->m_activeList.m_info[cnt].m_counterMask = 0;

        }

        for (cnt = 0; cnt < attrCnt; cnt++)
        {
            AMDTUInt16 idx = *(clientAttrList + cnt);

            if (DGPU_COUNTER_BASE_ID <= idx)
            {
                AMDTUInt32 loop = 0;
                AMDTUInt32 counterId = (idx - DGPU_COUNTER_BASE_ID) % DGPU_COUNTERS_MAX;

                //Find the correct package id for this counter
                AMDTUInt32 pkgId = APU_SMU_ID + ((idx - DGPU_COUNTER_BASE_ID) / DGPU_COUNTERS_MAX) + 1;

                for (loop = 0; loop < cfg->m_activeList.m_count; loop++)
                {
                    if (cfg->m_activeList.m_info[loop].m_packageId == pkgId)
                    {
                        cfg->m_activeList.m_info[loop].m_counterMask |= (1ULL << counterId);
                        break;
                    }
                }
            }
            else
            {
                AMDTPwrProfileAttrType id;
                id = (AMDTPwrProfileAttrType)(supportedList.pAttrList + idx)->m_attrId;
                SetRawAttributeMask((AMDTUInt16)id, pMask);

                if ((COUNTERID_SVI2_CORE_TELEMETRY == id)
                    || (COUNTERID_SVI2_NB_TELEMETRY == id))
                {
                    g_isSvi2Selected = true;
                }
            }
        }

        if (*pMask & SMU_ATTRIBUTE_MASK)
        {
            cfg->m_activeList.m_info[0].m_counterMask = (*pMask & SMU_ATTRIBUTE_MASK);
        }
    }

    return ret;
}

// Bios message service registers
#define SMU7_CPU_INT_STATUS                       0xC2100004
#define SMU7_CPU_INT_ARGUMENT                     0xC210003C
#define SMU7_CPU_INT_REQUEST                      0xC2100000
#define SMU7_PWR_FEATURE_MASK                     0x13
#define SMU7_BAPM_ON_BIT                          8
#define SMU7_GPU_CAC_ON_BIT                       15
#define SMU7_PKG_PWR_LIMITING_BIT                 23
#define SMU7_BIOSSMC_MSG_ENABLE_ALL_SMU_FEATURES  0x5F
#define SMU7_BIOSSMC_MSG_DISABLE_ALL_SMU_FEATURES 0x60
#define ENABLE_ALL_SMU7_FEATURES                  0x5F
#define ENABLE_ALL_SMU7_FEAUTRE_MASK              0x13
#define SMU7_FEATURE_STATUS_REGISTER              0x3f818
//NB Spec registers
#define SMU_INDEX_ADDR        0x800000B8
#define SMU_INDEX_DATA        0x800000BC

// AccessBCB8Pairs: Access SMU BC B8 pairs
bool AccessBCB8Pairs(AMDTUInt32 reg, AMDTUInt32* pData, bool isRead)
{
    bool ret = false;
    AMDTResult res = AMDT_STATUS_OK;
    ACCESS_PCI pciData;
    pciData.address = SMU_INDEX_ADDR;
    pciData.data = reg;
    pciData.isReadAccess = false;

    // Write index register
    res = AccessPciAddress(&pciData);

    if (AMDT_STATUS_OK == res)
    {
        // Read SMU soft register
        pciData.address = SMU_INDEX_DATA;
        pciData.isReadAccess = isRead;
        AccessPciAddress(&pciData);
        *pData = pciData.data;
        ret = true;
    }

    return ret;
}

// PwrIsSVISupported: Check if SVI2 is supported
bool PwrIsSVISupported(const AMDTPwrTargetSystemInfo& sysInfo)
{
    bool ret = false;

    if (nullptr != sysInfo.m_pNodeInfo)
    {
        HardwareType type = sysInfo.m_pNodeInfo->m_hardwareType;

        if ((GDT_SPECTRE == type)
            || (GDT_SPECTRE_LITE == type)
            || (GDT_SPECTRE_SL == type)
            || (GDT_KALINDI == type))
        {
            ret = true;
        }
        else
        {
            PwrTrace("SVI2 counters are not supported in this platform");
        }
    }

    return ret;
}

// PwrIsInternalCounterAvailable: Check if internal counters are available
bool PwrIsInternalCounterAvailable()
{
    bool ret = false;
    FILE* pFile = nullptr;

    memset(&g_internalCounterAddr, 0 , sizeof(PwrInternalAddr));
    // For writing the file
    //ret = PwrOpenFile(&pFile, "AMDTPwrInternalCounter.bin", "wb");
    //ret = PwrWriteFile(pFile, (AMDTUInt8*)&g_internalCounterAddr, sizeof(PwrInternalAddr));

    // Read internal counter address file
    ret = PwrOpenFile(&pFile, "Data\\AMDTPwrInternalCounter.bin", "r");

    // If internal file is available update the address from internal file
    // else reset all address to 0
    if (ret)
    {
        // Read the file into the buffer:
        ret = PwrReadFile(pFile, (AMDTUInt8*)&g_internalCounterAddr, sizeof(PwrInternalAddr));
    }
    else
    {
        PwrTrace("Internal Counters are not available");
    }

    return ret;
}

// PwrWriteInternalCounterAddres: Write internal counter information to shared buffer
void PwrWriteInternalCounterAddres()
{
    if (nullptr != g_pSharedBuffer)
    {
        memcpy((PwrInternalAddr*)&g_pSharedBuffer[PWR_INTERNAL_COUNTER_BASE], &g_internalCounterAddr, sizeof(PwrInternalAddr));
    }
}

// IsSMUFeatureEnabled:  Check if BAPM/ PKG power limiting etc are enabled
bool IsSMUFeatureEnabled()
{

    AMDTUInt32 statusReg = 0;
    bool ret = false;
    AMDTResult result = false;
    ACCESS_PCI pciData;
    pciData.address = SMU_INDEX_ADDR;
    pciData.data = SMU7_FEATURE_STATUS_REGISTER;
    pciData.isReadAccess = false;

    // Write index register
    result = AccessPciAddress(&pciData);

    if (AMDT_STATUS_OK == result)
    {
        // Read SMU soft register
        pciData.address = SMU_INDEX_DATA;
        pciData.isReadAccess = true;
        AccessPciAddress(&pciData);
        statusReg = pciData.data;
    }

    ret = (statusReg & (1 << SMU7_BAPM_ON_BIT)) ? 1 : 0;
    ret &= (statusReg & (1 << SMU7_GPU_CAC_ON_BIT)) ? 1 : 0;
    ret &= (statusReg & (1 << SMU7_PKG_PWR_LIMITING_BIT)) ? 1 : 0;
    return ret;
}

// IsIGPUAvailable: Check if iGPU is available with B0D1F0x18 register
// refer to the BKDG for this register
bool IsIGPUAvailable()
{
    AMDTInt32 ret = AMDT_STATUS_OK;
    ACCESS_PCI pciData;

    GET_EXTENED_PCICS_ADDRESS(0x0U, 0x1U, 0x0U, 0x18U, pciData.address)
    pciData.isReadAccess = 1;

    //Get PCI Access
    ret = AccessPciAddress(&pciData);

    if (AMDT_STATUS_OK != ret)
    {
        PwrTrace("IsIGPUAvailable failed for PCIe access");
    }

    return (pciData.data < 0xFFFFFFFF ? true : false);
}

// PwrRegisterClient: Register client with the driver's client list and get a client id.
// Only one client is allowed at a time at this moment.
AMDTResult PwrRegisterClient(AMDTUInt32* clientId)
{
    AMDTInt32 ret = AMDT_STATUS_OK;
    AMDTInt32 res = 0;
    bool result = false;

    if (PowerProfilingInitialized != g_powerProfileState)
    {
        ret = AMDT_ERROR_ACCESSDENIED;
        PwrTrace("PwrRegisterClient failed as state not eq PowerProfilingInitialized");
    }

    if (AMDT_STATUS_OK == ret)
    {
        result = 0;
        //Check if driver is opened
        result = IsPowerDriverOpened();
    }

    if (!result)
    {
        ret = AMDT_ERROR_ACCESSDENIED;
        PwrTrace("IsPowerDriverOpened failed");
    }

    if (AMDT_STATUS_OK == ret)
    {
        // Register the client
        res = RegisterClientWithDriver(clientId);
    }

    if ((AMDT_STATUS_OK != res) || *clientId > (MAX_CLIENT_COUNT - 1))
    {
        ret = AMDT_ERROR_ACCESSDENIED;
        PwrTrace("RegisterClientWithDriver failed");
    }

    return ret;
}

// PwrSetProfilingConfiguration: Set profile configuration to the driver data structure
// so that driver can initiliaze and create required data structure and memories.
AMDTResult PwrSetProfilingConfiguration(
    /*in*/ AMDTPwrProfileConfig* pConfig)
{
    AMDTInt32 ret = AMDT_STATUS_OK;
    AMDTInt32 res = 0;
    PROF_CONFIGS cfgList;
    ProfileConfig cfg;
    memset(&cfgList, 0, sizeof(PROF_CONFIGS));

    if ((AMDT_STATUS_OK == ret) &&
        (!pConfig ||
         !pConfig->m_pAttrList ||
         !pConfig->m_pSpecList ||
         !pConfig->m_attrCnt ||
         //Number of spec is restricted to 1 at this moment
         pConfig->m_specCnt != 1))
    {
        ret = AMDT_ERROR_INVALIDARG;
        PwrTrace("PwrSetProfilingConfiguration failed: as one of the arg is invalid");
    }

    if (AMDT_STATUS_OK == ret)
    {
        ret = InitializeSharedBuffer();
    }

    if (AMDT_STATUS_OK == ret)
    {
        //Prepare the list for the driver
        AMDTPwrTargetSystemInfo sysInfo;
        AMDTPwrGetTargetSystemInfo(&sysInfo);
        memset(&cfg, 0, sizeof(cfg));
        memcpy(&cfg.m_activeList, &sysInfo.m_smuTable, sizeof(SmuList));
        cfgList.ulStatus = 0;
        cfgList.ulConfigCnt = 1;
        cfgList.uliProfileConfigs = reinterpret_cast<uint64>(&cfg);
        cfg.m_attrCnt = (AMDTUInt16)pConfig->m_attrCnt;
        cfg.m_samplingSpec.m_profileType = pConfig->m_pSpecList->m_profileType;
        cfg.m_apuCounterMask = 0;
        SetAttributeMask(pConfig->m_pAttrList, pConfig->m_attrCnt, &cfg);
        cfg.m_samplingSpec.m_samplingPeriod = (uint32)pConfig->m_pSpecList->m_samplingPeriod;

        //Set core mask count & mask
        cfg.m_samplingSpec.m_maskCnt = pConfig->m_pSpecList->m_maskCnt;
        cfg.m_samplingSpec.m_mask = pConfig->m_pSpecList->m_mask;

        cfgList.ulClientId = pConfig->m_clientId;

        // Check if internal counter file is present
        PwrWriteInternalCounterAddres();

        //Instruct driver for the configuration.
        ret = CommandPowerDriver(DRV_CMD_TYPE_IN_OUT,
                                 IOCTL_ADD_PROF_CONFIGS,
                                 &cfgList,
                                 sizeof(PROF_CONFIGS),
                                 &cfgList,
                                 sizeof(PROF_CONFIGS),
                                 &res);
    }

    if (PROF_ERROR_SMU_CONGIGURATION == cfgList.ulStatus)
    {
        ret = AMDT_ERROR_BIOS_VERSION_NOT_SUPPORTED;
    }

    if (AMDT_STATUS_OK != ret)
    {
        PwrTrace("failed as IOCTL_ADD_PROF_CONFIGS failed");
    }

    return ret;
}

// EnableSVI2Telemetry: SVI2 telemetry voltage and current is supported
// only for internal version of Kavery & Mullins platform
bool EnableSVI2Telemetry(bool isEnable)
{
    AMDTResult ret = false;
    // Wait for the VOFT complete indication from the voltage regulator
    // before macking additional voltage change request
    ACCESS_PCI pci;
    pci.address = g_internalCounterAddr.m_timingControl4;
    pci.isReadAccess = false;
    pci.data = (1 << 30);
    ret = AccessPciAddress(&pci);

    if (AMDT_STATUS_OK == ret)
    {
        // Enable SVI2 now. Telemetry enable in Voltage & Current mode
        memset(&pci, 0, sizeof(ACCESS_PCI));
        pci.address = g_internalCounterAddr.m_timingControl6;
        pci.isReadAccess = false;

        if (true == isEnable)
        {
            pci.data = 0x01;
        }
        else
        {
            pci.data = 0x00;
        }

        ret = AccessPciAddress(&pci);
    }

    return (AMDT_STATUS_OK == ret) ? true : false;
}

//AMDTPwrStartProfiling- If the profiler is not running, this will start the profiler, and cause the
AMDTResult PwrStartProfiling()

{
    AMDTInt32 ret = AMDT_STATUS_OK;

    PROFILER_PROPERTIES param;
    AMDTUInt32 res = 0;
    AMDTUInt32 clientId = 0;

    memset(&param, 0, sizeof(PROFILER_PROPERTIES));

    //Check power profile state
    if ((PowerProfiling == g_powerProfileState) ||
        (PowerProfilingUnavailable == g_powerProfileState))
    {
        ret = AMDT_STATUS_PENDING;
        PwrTrace("Failed as state not correct %d", g_powerProfileState);
    }

    //Check if profiler is initialized
    if (PowerProfilingInitialized != g_powerProfileState)
    {
        ret = AMDT_ERROR_FAIL;
        PwrTrace("Failed: state %d", g_powerProfileState);
    }

    memset(&param, 0, sizeof(PROFILER_PROPERTIES));

    if (AMDT_STATUS_OK == ret)
    {
        //Check driver initialization is done
        ret = GetPowerDriverClientId(&clientId);
    }

    if (AMDT_STATUS_OK != ret)
    {
        ret = AMDT_ERROR_FAIL;
        PwrTrace("Failed: as GetPowerDriverClientId failed");
    }

    if (AMDT_STATUS_OK == ret)
    {

        if (true == g_isSvi2Selected)
        {
            // Enable SVI2
            // SVI2 is supported only on internal & CodeXL build and
            // for Kaveri & Mullins platforms
            if (g_internalCounters
                && g_isSVI2Supported)
            {
                EnableSVI2Telemetry(true);
            }
            else
            {
                g_isSvi2Selected = false;
            }
        }

        memset(&param, 0, sizeof(PROFILER_PROPERTIES));
        //IOCTL command to set the output file
        param.ulClientId = clientId;
        param.ulProfileMode = g_isOnline;

        param.hAbort = 0;
        ret = CommandPowerDriver(DRV_CMD_TYPE_IN_OUT,
                                 IOCTL_START_PROFILER,
                                 &param,
                                 sizeof(PROFILER_PROPERTIES),
                                 &param,
                                 sizeof(PROFILER_PROPERTIES),
                                 &res);
    }

    if (PROF_ERROR_SMU_CONGIGURATION == param.ulStatus)
    {
        ret = AMDT_ERROR_BIOS_VERSION_NOT_SUPPORTED;
    }

    g_powerProfileState = PowerProfiling;
    return ret;
}

//AMDTPwrStopProfiling- If the profiler is running, this will stop the profiler, and cause the
//state to go to ProfilingStopped.  If sampling, no further data will
//be written to the profile files.
AMDTResult PwrStopProfiling()
{
    AMDTInt32 ret = AMDT_STATUS_OK;
    AMDTInt32 res = 0;
    AMDTInt32 status = 0;
    AMDTUInt32 clientId = 0;

    //Check the status of the power profiling
    if ((PowerProfiling != g_powerProfileState) && (PowerProfilingPaused != g_powerProfileState))
    {
        ret = AMDT_ERROR_FAIL;
        PwrTrace("PwrStopProfiling failed: as state not correct %d", g_powerProfileState);
    }

    if (AMDT_STATUS_OK == ret)
    {
        ret = GetPowerDriverClientId(&clientId);
    }

    if (AMDT_STATUS_OK == ret)
    {
        //Stop the driver
        ret = CommandPowerDriver(DRV_CMD_TYPE_IN_OUT,
                                 IOCTL_STOP_PROFILER,
                                 &clientId,
                                 sizeof(AMDTUInt64),
                                 &status,
                                 sizeof(AMDTUInt64),
                                 &res);
    }

    if (AMDT_STATUS_OK == ret)
    {
        if (true == g_isSvi2Selected)
        {
            // SVI2 votlage and current is enables. So need to disable now
            EnableSVI2Telemetry(false);
        }

        g_powerProfileState = PowerProfilingStopped;
        PwrProfileUnregisterClient();
    }
    else
    {
        PwrTrace("PwrStopProfiling failed: as IOCTL_STOP_PROFILER failed");
    }

    return ret;
}

//AMDTPwrPauseProfiling- If the profiler is running, this will pause the profiler
AMDTResult PwrPauseProfiling()
{
    AMDTInt32 ret = AMDT_STATUS_OK;
    AMDTInt32 res = 0;
    AMDTInt32 status = 0;
    AMDTUInt32 clientId = 0;

    //Check the status of the power profiling
    if (PowerProfiling != g_powerProfileState)
    {
        ret = AMDT_ERROR_FAIL;
        PwrTrace("PwrPauseProfiling failed: as state not correct %d", g_powerProfileState);
    }

    if (AMDT_STATUS_OK == ret)
    {
        ret = GetPowerDriverClientId(&clientId);
    }

    if (AMDT_STATUS_OK == ret)
    {

        //Stop the driver
        ret = CommandPowerDriver(DRV_CMD_TYPE_IN_OUT,
                                 IOCTL_PAUSE_PROFILER,
                                 &clientId,
                                 sizeof(AMDTUInt32),
                                 &status,
                                 sizeof(AMDTUInt32),
                                 &res);

        if (AMDT_STATUS_OK != ret)
        {
            PwrTrace("PwrPauseProfiling failed: as IOCTL_PAUSE_PROFILER failed");
        }
    }

    g_powerProfileState = PowerProfilingPaused;

    return ret;
}

//int AMDTPwrResumeProfiling()- If the profiler is in paused state, this will resume the profiler
AMDTResult PwrResumeProfiling()

{
    AMDTInt32 ret = AMDT_STATUS_OK;
    AMDTInt32 res = 0;
    AMDTInt32 status = 0;
    AMDTUInt32 clientId = 0;

    //Check the status of the power profiling
    if (PowerProfilingPaused != g_powerProfileState)
    {
        ret = AMDT_ERROR_FAIL;
        PwrTrace("PwrResumeProfiling failed: as state not correct %d", g_powerProfileState);
    }

    if (AMDT_STATUS_OK == ret)
    {
        ret = GetPowerDriverClientId(&clientId);
    }

    if (AMDT_STATUS_OK == ret)
    {
        //Stop the driver
        ret = CommandPowerDriver(DRV_CMD_TYPE_IN_OUT,
                                 IOCTL_RESUME_PROFILER,
                                 &clientId,
                                 sizeof(AMDTUInt32),
                                 &status,
                                 sizeof(AMDTUInt32),
                                 &res);
    }

    if (AMDT_STATUS_OK != ret)
    {
        PwrTrace("PwrResumeProfiling failed: as IOCTL_RESUME_PROFILER failed");
    }

    g_powerProfileState = PowerProfiling;

    return ret;
}

// PwrGetProfilingState: Provides the current state of power profiling state machine
AMDTResult PwrGetProfilingState(
    /*out*/AMDTPwrProfilingState* pState)
{
    *pState = g_powerProfileState;
    return AMDT_STATUS_OK;
}

// PwrSetProfilingState: Allows to set the profile state
AMDTResult PwrSetProfilingState(
    /*in*/AMDTPwrProfilingState state)
{
    g_powerProfileState = state;
    return AMDT_STATUS_OK;
}

// PrepareApuPstateTable: Prepare the pstate table with harware/boosted pstates
// and their corresponding frequency.
void PrepareApuPstateTable()
{
    AMDTUInt32 boostedStates = 0;
    AMDTUInt64 regVal = 0;
    AMDTUInt32 cnt = 0;
    g_pStateInfo.m_cnt = AMDT_MAX_PSTATES;
    AMDTUInt32 reg = AMDT_PSTATE_BASE_REGISTER;

    // Get the number of boosted pstates from D18F4x15C
    ReadPciAddress(0, 0x18, 0x4, 0x15C, &boostedStates);

    // bits 4:2 are NumBoostStates
    boostedStates = ((boostedStates & 0x1C) >> 2);

    for (cnt = 0; cnt < AMDT_MAX_PSTATES; cnt++)
    {
        ACCESS_MSR msr;
        msr.isReadAccess = true;
        msr.regId = reg;
        AccessMSRAddress(&msr);
        regVal = msr.data;

        g_pStateInfo.m_stateInfo[cnt].m_frequency = (AMDTUInt32)(100.0 * (AMDTFloat64)((regVal & AMDT_CPUFID_MASK) + 0x10) /
                                                                 (AMDTFloat64)(0x1 << ((regVal & AMDT_CPUDID_MASK) >> AMDT_CPUDID_BITSHIFT)));

        if (cnt < boostedStates)
        {
            g_pStateInfo.m_stateInfo[cnt].m_isBoosted = true;
            g_pStateInfo.m_stateInfo[cnt].m_state = (AMDTApuPStates)(AMDT_PWR_PSTATE_PB0 + cnt);
        }
        else
        {
            g_pStateInfo.m_stateInfo[cnt].m_isBoosted = false;
            g_pStateInfo.m_stateInfo[cnt].m_state = (AMDTApuPStates)(AMDT_PWR_PSTATE_P0 + (cnt - boostedStates));
        }

        reg++;
    }

}

// GetApuPStateInfo: Function to access Apu pstate list information
AMDTPwrApuPstateList* GetApuPStateInfo()
{
    return &g_pStateInfo;
}

// check if NPU/CPU with NO SMU is supported
bool isNpuCpuPlatform(const AMDTUInt32& family, const AMDTUInt32& model)
{
    bool ret = false;

    for (PlatformInfo info : g_platformTable)
    {
        if (family == info.m_family)
        {
            if ((info.m_modelLow <= model) &&
                (model <= info.m_modelHigh))
            {
                ret = true;
            }
        }
    }

    return ret;
}

// AMDTPwrGetTargetSystemInfo: Hardware information of the target system where
// profiler was run
AMDTResult AMDTPwrGetTargetSystemInfo(
    /*in*/ AMDTPwrTargetSystemInfo* pSystemInfo)
{
    AMDTInt32 ret = AMDT_STATUS_OK;
    ACCESS_PCI pciData;
    AMDTUInt32 family = 0;
    AMDTUInt32 model = 0;
    bool isAmd = false;

    if (NULL == g_pTargetSystemInfo)
    {
        g_pTargetSystemInfo = (AMDTPwrTargetSystemInfo*) malloc(sizeof(AMDTPwrTargetSystemInfo));

        if (NULL == g_pTargetSystemInfo)
        {
            ret = AMDT_ERROR_OUTOFMEMORY;
        }

        if (AMDT_STATUS_OK == ret)
        {
            // Clear the structure first
            memset(g_pTargetSystemInfo, 0, sizeof(AMDTPwrTargetSystemInfo));

            // Get platform id
            g_pTargetSystemInfo->m_platformId = GetSupportedTargetPlatformId();
            ret = GetCpuFamilyDetails(&family, &model, &isAmd);
            g_pTargetSystemInfo->m_family = family;
            g_pTargetSystemInfo->m_model = model;
            g_pTargetSystemInfo->m_isAmd = isAmd;

            //Get core count
            g_pTargetSystemInfo->m_coreCnt = GetActiveCoreCount();
            g_pTargetSystemInfo->m_smuTable.m_count = 0;
            g_pTargetSystemInfo->m_isPlatformSupported = false;

            GetAvailableSmuList(&g_pTargetSystemInfo->m_smuTable);

            // Supported platform
            // APU+SMU , NPU and CPU
            if ((true == isAmd)
                && ((true == g_pTargetSystemInfo->m_isAmdApu)
                    || (true == isNpuCpuPlatform(family, model))))
            {
                g_pTargetSystemInfo->m_isPlatformSupported = true;
            }

            // If node platform is not supported and no valid dgpu connected
            if ((0 == g_pTargetSystemInfo->m_smuTable.m_count)
                && (false == g_pTargetSystemInfo->m_isPlatformSupported))
            {
                ret = AMDT_ERROR_PLATFORM_NOT_SUPPORTED;
            }
        }

        if ((AMDT_STATUS_OK == ret) && (true == isAmd))
        {
            if (NULL != g_pTargetSystemInfo->m_pNodeInfo)
            {
                // ONLY FOR SUPPORTED AMD platforms
                if (DEVICE_TYPE_APU == g_pTargetSystemInfo->m_pNodeInfo->m_deviceType)
                {
                    // Get compute unit count ONLY FOR SUPPORTED AMD APU
                    GET_EXTENED_PCICS_ADDRESS(0x0U, 0x18U, 0x5U, 0x80U, pciData.address);
                    pciData.isReadAccess = 1;
                    // Get PCI Access
                    ret = AccessPciAddress(&pciData);

                    if (AMDT_STATUS_OK == ret)
                    {
                        if (GDT_KALINDI == g_pTargetSystemInfo->m_pNodeInfo->m_hardwareType)
                        {
                            // Mullins has only one compute unit. Refer D1F5x80 Compute Unit Status 1
                            g_pTargetSystemInfo->m_computeUnitCnt = 1;
                            g_pTargetSystemInfo->m_coresPerCu = g_pTargetSystemInfo->m_coreCnt;
                        }
                        else
                        {
                            DecodeCURegisterStatus(pciData.data,
                                                   &g_pTargetSystemInfo->m_computeUnitCnt,
                                                   &g_pTargetSystemInfo->m_coresPerCu);
                        }

                        //Hard coding the remaing as of now
                        g_pTargetSystemInfo->m_igpuCnt = 1;
                        g_pTargetSystemInfo->m_svi2Cnt = 1;
                    }

                }

                // Fill the pState frequency table
                PrepareApuPstateTable();
            }
        }
    }

    if (AMDT_STATUS_OK == ret)
    {
        memcpy(pSystemInfo, g_pTargetSystemInfo, sizeof(AMDTPwrTargetSystemInfo));
    }

    return ret;
}

// Create memory pool: memory pool creation for interel use
AMDTResult CreateMemoryPool(MemoryPool* pPool, AMDTUInt32 size)
{
    AMDTResult ret = AMDT_ERROR_OUTOFMEMORY;

    if (NULL != pPool)
    {
        pPool->m_pBase = (AMDTUInt8*)malloc(size);

        if (NULL != pPool->m_pBase)
        {
            pPool->m_offset = 0;
            pPool->m_size = size;
            ret = AMDT_STATUS_OK;
        }
    }

    return ret;
}

// Get buffer from the pool pointer
AMDTUInt8* GetMemoryPoolBuffer(MemoryPool* pPool, AMDTUInt32 size)
{
    AMDTUInt8* pBuffer = NULL;

    if ((NULL == pPool) || ((pPool->m_offset + size) > pPool->m_size))
    {
        pBuffer = NULL;

        // Serious error -print the error message?
    }
    else
    {
        pBuffer = pPool->m_pBase + pPool->m_offset;
        pPool->m_offset += size;
    }

    return pBuffer;
}

// Delete the memory pool
AMDTResult ReleaseMemoryPool(MemoryPool* pPool)
{
    if (NULL != pPool)
    {
        if (NULL != pPool->m_pBase)
        {
            free(pPool->m_pBase);
            pPool->m_pBase = NULL;
            pPool->m_size = 0;
            pPool->m_offset = 0;
        }
    }

    return AMDT_STATUS_OK;
}

// GetAmdSupportedDevInfo: Get the dgpu information with the device id
bool GetAmdSupportedDevInfo(uint32 deviceId, PciDeviceInfo** pInfo)
{
    bool ret = false;
    AMDTUInt32 cnt = 0;
    AMDTUInt32 tableSize = sizeof(g_deviceTable) / sizeof(PciDeviceInfo);

    for (cnt = 0; cnt < tableSize; cnt++)
    {
        if (deviceId == g_deviceTable[cnt].m_deviceId)
        {
            *pInfo = &g_deviceTable[cnt];
            ret = true;
            break;
        }
    }

    return ret;
}

// GetAmdDeviceInfo: Get all AMD device information
bool GetAmdDeviceInfo(AMDTUInt32 bus,
                      AMDTUInt32 dev,
                      AMDTUInt32 func,
                      AMDTUInt32* pVendorId,
                      AMDTUInt32* pDeviceId)
{
    bool ret = false;
    ACCESS_PCI pci;
    GET_EXTENED_PCICS_ADDRESS(bus, dev, func, 0, pci.address);
    pci.isReadAccess = true;

    if (AMDT_STATUS_OK == AccessPciAddress(&pci))
    {
        *pVendorId = pci.data & 0xFFFF;
        *pDeviceId = pci.data >> 16;
        ret = true;
    }

    return ret;
}

// Smu8SRBMMsg: User spce SRBM message implementation for quick access
static bool Smu8SRBMMsg(SmuInfo* pSmu, uint32 msgId, uint32* argv, uint32* pData, uint32 retry)
{
    bool ret = false;
    uint32 repeatCnt = retry;
    uint64 msg = 0;
    uint64 resp = 0;
    uint32 data = 0;
    uint64 arg = 0;

    msg = pSmu->m_gpuBaseAddress + SMU8_SMC_MESSAGE_0;
    resp = pSmu->m_gpuBaseAddress + SMU8_SMC_RESPONSE_0;
    arg = pSmu->m_gpuBaseAddress + SMU8_SMC_MESSAGE_ARG_0;

    // 1.Driver clears SMU_MP1_SRBM2P_RESP_9 to 0. SMU firmware will write a non-zero response on message completion
    WriteMMIOSpace(resp, data);

    // 2.Driver optionally writes message arguments to SMU_MP1_SRBM2P_ARG_9.
    // SMU firmware may use the arguments for additional information depending on the message
    if (NULL != argv)
    {
        WriteMMIOSpace(arg, *argv);
    }

    // 3.Driver writes message ID to SMU_MP1_SRBM2P_MSG_9.
    WriteMMIOSpace(msg, msgId);

    // 4.Driver polls SMU_MP1_SRBM2P_RESP_9 until it reads back a non-zero response.
    do
    {
        ReadMMIOSpace(resp, &data);

        if (data & 0x01)
        {
            ret = true;
        }
    }
    while ((false == ret) && --repeatCnt);

    // 5.Driver optionally reads message arguments from SMU_MP1_SRBM2P_ARG_9. SMU firmware may
    // have updated this register depending on the message.
    if ((true == ret) && (NULL != pData))
    {
        ReadMMIOSpace(arg, pData);
    }

    return (true == ret) ? true : false;
}

// Smu7DriverMsg: User spce driver message implementation for quick access
bool Smu7DriverMsg(SmuInfo* pSmu, uint32 msgId)
{
    volatile uint32 cnt = 0;
    bool result = false;
    AMDTUInt32 data = 0;

    if (NULL != pSmu)
    {
        uint64 msg = pSmu->m_gpuBaseAddress + SMU7_SMC_MESSAGE_0;
        uint64 resp = pSmu->m_gpuBaseAddress + SMU7_SMC_RESPONSE_0;
        uint64 arg = pSmu->m_gpuBaseAddress + SMU7_SMC_MESSAGE_ARG_0;

        // MSG_RESP register should be non-zero before writing into MSG_ARG or MSG
        // register; If MSG_RESP is non-zero then SMU is ready for the next message.
        for (cnt = 0; cnt < SMU_RETRY_COUNT_MAX && (! result); ++cnt)
        {
            ReadMMIOSpace(resp, &data);

            if (0 != data)
            {
                result = true;
            }
        }

        if (result)
        {
            data = 0;
            WriteMMIOSpace(arg, data);

            // write the message into MSG register;
            WriteMMIOSpace(msg, msgId);

            ReadMMIOSpace(resp, &data);

            // wait for the opration to complete
            for (cnt = 0; cnt < SMU_RETRY_COUNT_MAX; ++cnt)
            {
                if (0 != data)
                {
                    break;
                }
            }

            ReadMMIOSpace(resp, &data);
            result = (1 == data) ? true : false;
        }
    }

    return result;
}

// IsDgpuMMIOAccessible: For AMD dGPU get the command register and
// check MMIO access bit is set
bool IsDgpuMMIOAccessible(AMDTUInt32 bus, AMDTUInt32 dev, AMDTUInt32 func)
{
    bool ret = false;
    ACCESS_PCI pci;
    GET_EXTENED_PCICS_ADDRESS(bus, dev, func, 4, pci.address);

    pci.isReadAccess = true;

    if (AMDT_STATUS_OK == AccessPciAddress(&pci))
    {
        ret = (pci.data & 0x2) ? true : false;
        PwrTrace("\nCommand reg 0x%x", pci.data);
    }

    return ret;
}

// IsSmuLogAccessible: Check if Smu longing for a particular device is successful
// This function will try for MAX_RETRY_COUNT time to access the smu logging
bool IsSmuLogAccessible(SmuInfo* pSmu, DeviceType devType)
{
    // SMU Message Commands used to START & SAMPLE the PM status logging
    AMDTUInt32 tabId = 0x01;
    bool ret = false;

    switch (pSmu->m_smuIpVersion)
    {
        case SMU_IPVERSION_8_0:
        case SMU_IPVERSION_8_1:
        {
            AMDTUInt32 tableBaseAddr = 0;
            // We can make sure smu is accessible by acquiring the AGM table base
            // address and release the table properly
            ret = Smu8SRBMMsg(pSmu,
                              SMU8_TESTSMC_MSG_RequestDataTable,
                              &tabId,
                              &tableBaseAddr,
                              SMU_RETRY_COUNT_MAX);
            Smu8SRBMMsg(pSmu,
                        0x40,
                        NULL,
                        &pSmu->m_access.m_smu8.m_tableVersion,
                        SMU_RETRY_COUNT_MAX);

            if (true == ret)
            {
                // Stop logging now
                ret = Smu8SRBMMsg(pSmu,
                                  SMU8_TESTSMC_MSG_ReleaseDataTable,
                                  NULL,
                                  NULL,
                                  SMU_RETRY_COUNT_MAX);

                if (false == ret)
                {
                    PwrTrace("IsSmuLogAccessible: SMU8_TESTSMC_MSG_ReleaseDataTable failed");
                }
            }
            else
            {
                PwrTrace("IsSmuLogAccessible: SMU8_TESTSMC_MSG_RequestDataTable failed");
            }

            break;
        }

        default:
        {
            if (DEVICE_TYPE_DGPU == devType)
            {
                ret = true;
            }
            else
            {
                AMDTUInt32 retry = SMU_LOG_MSG_RETRY_MAX;

                do
                {
                    // Initiate smu logging and stop loggin to check if smu is accessible
                    ret = Smu7DriverMsg(pSmu, SMU_PM_STATUS_LOG_START);

                    if (true == ret)
                    {
                        break;
                    }

                    SLEEP_IN_MS(50);
                }
                while (--retry);

                PwrTrace("Smu7DriverMsg: rety cnt %d", SMU_LOG_MSG_RETRY_MAX - retry);

                if (false == ret)
                {
                    PwrTrace("IsSmuLogAccessible: SMU_PM_STATUS_LOG_START failed");
                }
            }

            break;
        }
    }

    return ret;
}

// FillSmu7Details: Fill all register and offset details for smu7.
// Driver is open source. So we can not keep this information in driver
void FillSmu7Details(Smu7Interface* pSmu7Interface, PciDeviceInfo* pDev)
{
    Smu7CounterTable table =
    {
        SMU7_CU0_PWR,
        SMU7_CU1_PWR,
        SMU7_CU0_CALC_TEMP,
        SMU7_CU1_CALC_TEMP,
        SMU7_CU0_MEAS_TEMP,
        SMU7_CU1_MEAS_TEMP,
        SMU7_GPU_PWR,
        SMU7_PCIE_PWR,
        SMU7_DDR_PWR,
        SMU7_DISPLAY_PWR,
        SMU7_PACKAGE_PWR,
        SMU7_GPU_CALC_TEMP,
        SMU7_GPU_MEAS_TEMP,
        SMU7_SCLK,
        SMU7_VOLT_VDDC_LOAD,
        SMU7_CURR_VDDC
    };
    Smu7MessageParam msg = {SMU7_SMC_MESSAGE_0, SMU7_SMC_RESPONSE_0, SMU7_SMC_MESSAGE_ARG_0, 0};
    Smu7Logging logging = {SMU_PM_STATUS_LOG_START, SMU_PM_STATUS_LOG_SAMPLE};
    Smu7IndexData indexData = {SMC_IND_INDEX_2, SMC_IND_DATA_2};

    if (nullptr != pSmu7Interface)
    {
        // Consider calculated voltage & current in case of Bonaire
        if ((nullptr != pDev) && (GDT_BONAIRE == pDev->m_hardwareType))
        {
            table.m_voltVddcLoad = SMU7_VOLT_VDDC_LOAD_CALC;
            table.m_currVddc = SMU7_CURR_VDDC_CALC;
        }

        memcpy(&pSmu7Interface->m_counterTable, &table, sizeof(Smu7CounterTable));
        memcpy(&pSmu7Interface->m_messageParam, &msg, sizeof(Smu7MessageParam));
        memcpy(&pSmu7Interface->m_logging, &logging, sizeof(Smu7Logging));
        memcpy(&pSmu7Interface->m_indexData, &indexData, sizeof(Smu7IndexData));
    }
}

// FillSmu8Details:  Fill all register and offset details for smu8.
// Driver is open source. So we can not keep this information in driver
bool FillSmu8Details(Smu8Interface* pSmu)
{
    bool result = false;
    Smu8SRBMMessage srbmMsgTable = { SMU8_SMC_MESSAGE_0 - MAPPED_BASE_OFFSET,
                                     SMU8_SMC_MESSAGE_ARG_0 - MAPPED_BASE_OFFSET,
                                     SMU8_SMC_RESPONSE_0 - MAPPED_BASE_OFFSET,
                                     SMU8_TESTSMC_MSG_RequestDataTable,
                                     SMU8_TESTSMC_MSG_ReleaseDataTable,
    {0x00}
                                   };

    Smu8MMAccess memAccessTable = {MAPPED_BASE_OFFSET - MAPPED_BASE_OFFSET,
                                   0x60C - MAPPED_BASE_OFFSET
                                  };

    if (NULL != pSmu)
    {
        // Reset the information
        pSmu->m_tableId = 0x01;
        memcpy(&pSmu->m_srbmMsg, &srbmMsgTable, sizeof(Smu8SRBMMessage));
        memcpy(&pSmu->m_gmmxPair, &memAccessTable, sizeof(Smu8MMAccess));

        result = true;
    }

    return result;
}

// GetAvailableSmuList: Prepare SMU lists for the all hardware including APU
// and dGPU connected to the platform
bool GetAvailableSmuList(SmuList* pList)
{
    bool ret = false;
    AMDTUInt32 devCnt = 0;
    AMDTUInt32 busCnt = 0;
    AMDTUInt32 funcCnt = 0;
    uint32 smuCnt = 0;
    uint32 dgpuCnt = APU_SMU_ID + 1;

    if (NULL != pList && (0 == pList->m_count))
    {
        // Clear the dgpu short name table
        memset(&g_activePciDevice[0], 0, sizeof(g_activePciDevice));
        memset(&g_activePciPortList[0], 0, sizeof(g_activePciPortList));
        g_pTargetSystemInfo->m_pNodeInfo = NULL;

        for (busCnt = 0; (pList->m_count < PLATFORM_SMU_CNT) && busCnt < MAX_BUS_CNT; busCnt++)
        {
            for (devCnt = 0; (pList->m_count < PLATFORM_SMU_CNT) && devCnt < MAX_PCIE_DEVICE_CNT; devCnt++)
            {
                for (funcCnt = 0; (pList->m_count < PLATFORM_SMU_CNT) && funcCnt < MAX_FUNCTION_CNT; funcCnt++)
                {
                    uint32 vendorId = 0;
                    uint32 deviceId = 0;

                    if (true == GetAmdDeviceInfo(busCnt, devCnt, funcCnt, &vendorId, &deviceId))
                    {
                        if (0xFFFFFFFF == (vendorId | deviceId << 15))
                        {
                            break;
                        }

                        if (AMD_VENDOR_ID == vendorId)
                        {
                            PciDeviceInfo* pDevInfo = NULL;

                            if (true == GetAmdSupportedDevInfo(deviceId, &pDevInfo)
                                && (pList->m_count < PLATFORM_SMU_CNT))
                            {
                                bool smuAccess = false;
                                bool mmioAccess = true;
                                bool apuSmuFeature = true;

                                if ((DEVICE_TYPE_APU == pDevInfo->m_deviceType) || (DEVICE_TYPE_DGPU == pDevInfo->m_deviceType))
                                {
                                    // Fill only if this is an SMU
                                    AMDTUInt32 res = 0x00;
                                    // AMDTUInt32 pkgId = dgpuCnt++;
                                    pList->m_info[smuCnt].m_packageId = (DEVICE_TYPE_APU == pDevInfo->m_deviceType) ? APU_SMU_ID : dgpuCnt++;
                                    pList->m_info[smuCnt].m_smuIpVersion = pDevInfo->m_smuIpVersion;
                                    ReadPciAddress(busCnt, devCnt, funcCnt, 0x24, &res);
                                    pList->m_info[smuCnt].m_gpuBaseAddress = res & 0xFFFFFFF0;
                                    pList->m_count += 1;

                                    // Fill the device information
                                    memcpy(&g_activePciDevice[pList->m_info[smuCnt].m_packageId], pDevInfo, sizeof(PciDeviceInfo));
                                    g_activePciPortList[pList->m_info[smuCnt].m_packageId].m_bus = busCnt;
                                    g_activePciPortList[pList->m_info[smuCnt].m_packageId].m_dev = devCnt;
                                    g_activePciPortList[pList->m_info[smuCnt].m_packageId].m_func = funcCnt;

                                    // Fill SMU values
                                    if ((SMU_IPVERSION_7_0 == pDevInfo->m_smuIpVersion)
                                        || (SMU_IPVERSION_7_1 == pDevInfo->m_smuIpVersion)
                                        || (SMU_IPVERSION_7_5 == pDevInfo->m_smuIpVersion)
                                       )
                                    {
                                        FillSmu7Details(&pList->m_info[smuCnt].m_access.m_smu7, pDevInfo);
                                    }
                                    else if ((SMU_IPVERSION_8_0 == pDevInfo->m_smuIpVersion)
                                             || (SMU_IPVERSION_8_1 == pDevInfo->m_smuIpVersion))
                                    {
                                        FillSmu8Details(&pList->m_info[smuCnt].m_access.m_smu8);
                                    }

                                    if (DEVICE_TYPE_APU == pDevInfo->m_deviceType)
                                    {
                                        g_pTargetSystemInfo->m_isAmdApu = true;

                                        // Check if it is KV, if so, check if BAPM and smu feature is enable
                                        if ((GDT_SPECTRE == pDevInfo->m_hardwareType)
                                            || (GDT_SPECTRE_SL == pDevInfo->m_hardwareType)
                                            || (GDT_SPOOKY == pDevInfo->m_hardwareType)
                                            || (GDT_SPECTRE_LITE == pDevInfo->m_hardwareType))
                                        {
                                            apuSmuFeature = IsSMUFeatureEnabled();
                                        }
                                    }

                                    // If dGPU first check MMIO is accessible
                                    if (DEVICE_TYPE_DGPU == pDevInfo->m_deviceType)
                                    {
                                        mmioAccess = IsDgpuMMIOAccessible(busCnt, devCnt, funcCnt);
                                        PwrTrace("dGPU mmio access %d", mmioAccess);
                                    }

                                    if ((true == mmioAccess) && (true == apuSmuFeature))
                                    {
                                        smuAccess = IsSmuLogAccessible(&pList->m_info[smuCnt], pDevInfo->m_deviceType);
                                    }

                                    pList->m_info[smuCnt].m_isAccessible = smuAccess;
                                    smuCnt++;
                                }

                                if ((DEVICE_TYPE_APU == pDevInfo->m_deviceType)
                                    || (DEVICE_TYPE_CPU_NO_SMU == pDevInfo->m_deviceType)
                                    || (DEVICE_TYPE_NPU_NO_SMU == pDevInfo->m_deviceType))
                                {
                                    g_pTargetSystemInfo->m_pNodeInfo = pDevInfo;
                                }

                                PwrTrace(DEVICE_TRACE_STR,
                                         busCnt,
                                         devCnt,
                                         funcCnt,
                                         pDevInfo->m_deviceId,
                                         pDevInfo->m_hardwareType,
                                         pDevInfo->m_deviceType,
                                         pDevInfo->m_modelName,
                                         pDevInfo->m_shortName,
                                         pDevInfo->m_smuIpVersion,
                                         smuAccess);
                            }
                            else
                            {
                                PwrTrace("SMU not supported for device Id B%dD%df%d: 0x%x ",
                                         busCnt, devCnt, funcCnt, deviceId);
                            }
                        }
                    }
                }
            }
        }
    }

    ret = ((NULL != g_pTargetSystemInfo->m_pNodeInfo) || (0 < pList->m_count)) ? true : false;
    return ret;
}

// GetPcieDeviceInfo: Get the short name of each device and plaform
// connected
void GetPciDeviceInfo(AMDTUInt32 pkgId, PciDeviceInfo** ppDevInfo, PciPortAddress** ppAddress)
{
    if (nullptr != ppDevInfo)
    {
        *ppDevInfo = &g_activePciDevice[pkgId];
    }

    if (nullptr != ppAddress)
    {
        *ppAddress = &g_activePciPortList[pkgId];
    }
}


text:
using std::int32_t;
using std::uint32_t;

namespace RDKit {
const int32_t ReactionPickler::versionMajor = 2;
const int32_t ReactionPickler::versionMinor = 0;
const int32_t ReactionPickler::versionPatch = 0;
const int32_t ReactionPickler::endianId = 0xDEADBEEF;

void streamWrite(std::ostream &ss, ReactionPickler::Tags tag) {
  int32_t tmp = tag;
  streamWrite(ss, tmp);
}
template <typename T>
void streamWrite(std::ostream &ss, ReactionPickler::Tags tag, const T &what) {
  streamWrite(ss, tag);
  streamWrite(ss, what);
};

void streamRead(std::istream &ss, ReactionPickler::Tags &tag) {
  int32_t tmp;
  streamRead(ss, tmp);
  tag = static_cast<ReactionPickler::Tags>(tmp);
}

void ReactionPickler::pickleReaction(const ChemicalReaction *rxn,
                                     std::ostream &ss) {
  pickleReaction(rxn, ss, MolPickler::getDefaultPickleProperties());
}

void ReactionPickler::pickleReaction(const ChemicalReaction *rxn,
                                     std::ostream &ss,
                                     unsigned int propertyFlags) {
  PRECONDITION(rxn, "empty reaction");
  streamWrite(ss, endianId);
  streamWrite(ss, VERSION);
  streamWrite(ss, versionMajor);
  streamWrite(ss, versionMinor);
  streamWrite(ss, versionPatch);
  _pickle(rxn, ss, propertyFlags);
}

void ReactionPickler::pickleReaction(const ChemicalReaction *rxn,
                                     std::string &res) {
  pickleReaction(rxn, res, MolPickler::getDefaultPickleProperties());
}
void ReactionPickler::pickleReaction(const ChemicalReaction *rxn,
                                     std::string &res,
                                     unsigned int propertyFlags) {
  PRECONDITION(rxn, "empty reaction");
  std::stringstream ss(std::ios_base::binary | std::ios_base::out |
                       std::ios_base::in);
  ReactionPickler::pickleReaction(rxn, ss, propertyFlags);
  res = ss.str();
}

// NOTE: if the reaction passed in here already has reactants and products
// be left intact.
void ReactionPickler::reactionFromPickle(std::istream &ss,
                                         ChemicalReaction *rxn) {
  PRECONDITION(rxn, "empty reaction");
  Tags tag;
  int32_t tmpInt;

  streamRead(ss, tmpInt);
  if (tmpInt != endianId) {
    throw ReactionPicklerException(
        "Bad pickle format: bad endian ID or invalid file format");
  }

  streamRead(ss, tag);
  if (tag != VERSION) {
    throw ReactionPicklerException("Bad pickle format: no version tag");
  }
  int32_t majorVersion, minorVersion, patchVersion;
  streamRead(ss, majorVersion);
  streamRead(ss, minorVersion);
  streamRead(ss, patchVersion);
  if (majorVersion > versionMajor ||
      (majorVersion == versionMajor && minorVersion > versionMinor)) {
    BOOST_LOG(rdWarningLog)
        << "Depickling from a version number (" << majorVersion << "."
        << minorVersion << ")"
        << "that is higher than our version (" << versionMajor << "."
        << versionMinor << ").\nThis probably won't work." << std::endl;
  }
  majorVersion = 1000 * majorVersion + minorVersion * 10 + patchVersion;

  _depickle(ss, rxn, majorVersion);
}
void ReactionPickler::reactionFromPickle(const std::string &pickle,
                                         ChemicalReaction *rxn) {
  PRECONDITION(rxn, "empty reaction");
  std::stringstream ss(std::ios_base::binary | std::ios_base::out |
                       std::ios_base::in);
  ss.write(pickle.c_str(), pickle.length());
  ReactionPickler::reactionFromPickle(ss, rxn);
}

void ReactionPickler::_pickle(const ChemicalReaction *rxn, std::ostream &ss,
                              unsigned int propertyFlags) {
  PRECONDITION(rxn, "empty reaction");
  uint32_t tmpInt;

  tmpInt = static_cast<int32_t>(rxn->getNumReactantTemplates());
  streamWrite(ss, tmpInt);
  tmpInt = static_cast<int32_t>(rxn->getNumProductTemplates());
  streamWrite(ss, tmpInt);
  tmpInt = static_cast<int32_t>(rxn->getNumAgentTemplates());
  streamWrite(ss, tmpInt);

  uint32_t flag = 0;
  if (rxn->getImplicitPropertiesFlag()) {
    flag |= 0x1;
  }
  if (rxn->df_needsInit) {
    flag |= 0x2;
  }
  streamWrite(ss, flag);

  // -------------------
  //
  // Write Reactants
  //
  // -------------------
  streamWrite(ss, BEGINREACTANTS);
  for (auto tmpl = rxn->beginReactantTemplates();
       tmpl != rxn->endReactantTemplates(); ++tmpl) {
    MolPickler::pickleMol(tmpl->get(), ss);
  }
  streamWrite(ss, ENDREACTANTS);

  streamWrite(ss, BEGINPRODUCTS);
  for (auto tmpl = rxn->beginProductTemplates();
       tmpl != rxn->endProductTemplates(); ++tmpl) {
    MolPickler::pickleMol(tmpl->get(), ss,
                          PicklerOps::PropertyPickleOptions::AtomProps);
  }
  streamWrite(ss, ENDPRODUCTS);

  if (rxn->getNumAgentTemplates()) {
    streamWrite(ss, BEGINAGENTS);
    for (auto tmpl = rxn->beginAgentTemplates();
         tmpl != rxn->endAgentTemplates(); ++tmpl) {
      MolPickler::pickleMol(tmpl->get(), ss);
    }
    streamWrite(ss, ENDAGENTS);
  }

  if (propertyFlags & PicklerOps::MolProps) {
    streamWrite(ss, BEGINPROPS);
    _pickleProperties(ss, *rxn, propertyFlags);
    streamWrite(ss, ENDPROPS);
  }

  streamWrite(ss, ENDREACTION);
}  // end of _pickle

void ReactionPickler::_pickleProperties(std::ostream &ss, const RDProps &props,
                                        unsigned int pickleFlags) {
  if (!pickleFlags) {
    return;
  }

  streamWriteProps(ss, props, pickleFlags & PicklerOps::PrivateProps,
                   pickleFlags & PicklerOps::ComputedProps);
}

//! unpickle standard properties
void ReactionPickler::_unpickleProperties(std::istream &ss, RDProps &props) {
  streamReadProps(ss, props);
}

void ReactionPickler::_depickle(std::istream &ss, ChemicalReaction *rxn,
                                int version) {
  PRECONDITION(rxn, "empty reaction");

  Tags tag;
  uint32_t numReactants, numProducts, numAgents = 0;

  streamRead(ss, numReactants);
  streamRead(ss, numProducts);
  if (version > 1000) {
    streamRead(ss, numAgents);
  }
  // we use this here and below to set df_needsInit, so don't re-use the
  // variable
  uint32_t flag = 0;
  streamRead(ss, flag);
  rxn->setImplicitPropertiesFlag(flag & 0x1);

  // -------------------
  //
  // Read Reactants
  //
  // -------------------
  streamRead(ss, tag);
  if (tag != BEGINREACTANTS) {
    throw ReactionPicklerException(
        "Bad pickle format: BEGINREACTANTS tag not found.");
  }
  for (unsigned int i = 0; i < numReactants; ++i) {
    auto *mol = new RWMol();
    MolPickler::molFromPickle(ss, mol);
    rxn->addReactantTemplate(ROMOL_SPTR(mol));
  }
  streamRead(ss, tag);
  if (tag != ENDREACTANTS) {
    throw ReactionPicklerException(
        "Bad pickle format: ENDREACTANTS tag not found.");
  }
  streamRead(ss, tag);
  if (tag != BEGINPRODUCTS) {
    throw ReactionPicklerException(
        "Bad pickle format: BEGINPRODUCTS tag not found.");
  }
  for (unsigned int i = 0; i < numProducts; ++i) {
    auto *mol = new RWMol();
    MolPickler::molFromPickle(ss, mol);
    rxn->addProductTemplate(ROMOL_SPTR(mol));
  }
  streamRead(ss, tag);
  if (tag != ENDPRODUCTS) {
    throw ReactionPicklerException(
        "Bad pickle format: ENDPRODUCTS tag not found.");
  }
  if (numAgents != 0) {
    streamRead(ss, tag);
    if (tag != BEGINAGENTS) {
      throw ReactionPicklerException(
          "Bad pickle format: BEGINAGENTS tag not found.");
    }
    for (unsigned int i = 0; i < numAgents; ++i) {
      auto *mol = new RWMol();
      MolPickler::molFromPickle(ss, mol);
      rxn->addAgentTemplate(ROMOL_SPTR(mol));
    }
    streamRead(ss, tag);
    if (tag != ENDAGENTS) {
      throw ReactionPicklerException(
          "Bad pickle format: ENDAGENTS tag not found.");
    }
  }
  streamRead(ss, tag);
  if (tag == BEGINPROPS) {
    _unpickleProperties(ss, *rxn);
    streamRead(ss, tag);
    if (tag != ENDPROPS) {
      throw ReactionPicklerException(
          "Bad pickle format: ENDPROPS tag not found.");
    }
  }

  // need to do this after we add reactants and products
  rxn->df_needsInit = flag & 0x2;

}  // end of _depickle
};  // namespace RDKit

redpajama_set_name: RedPajamaGithub


text:
// Load modules

var Any = require('./any');
var Cast = require('./cast');
var Ref = require('./ref');

// Declare internals

var internals = {
    alternatives: require('./alternatives'),
    array: require('./array'),
    boolean: require('./boolean'),
    binary: require('./binary'),
    date: require('./date'),
    number: require('./number'),
    object: require('./object'),
    string: require('./string')
};

internals.root = function () {

    var any = new Any();

    var root = any.clone();
    root.any = function () {

        return any;
    };

    root.alternatives = root.alt = function () {

        return arguments.length ? internals.alternatives.try.apply(internals.alternatives, arguments) : internals.alternatives;
    };

    root.array = function () {

        return internals.array;
    };

    root.boolean = root.bool = function () {

        return internals.boolean;
    };

    root.binary = function () {

        return internals.binary;
    };

    root.date = function () {

        return internals.date;
    };

    root.func = function () {

        return internals.object._func();
    };

    root.number = function () {

        return internals.number;
    };

    root.object = function () {

        return arguments.length ? internals.object.keys.apply(internals.object, arguments) : internals.object;
    };

    root.string = function () {

        return internals.string;
    };

    root.ref = function () {

        return Ref.create.apply(null, arguments);
    };

    root.isRef = function (ref) {

        return Ref.isRef(ref);
    };

    root.validate = function (value /*, [schema], [options], callback */) {

        var last = arguments[arguments.length - 1];
        var callback = typeof last === 'function' ? last : null;

        var count = arguments.length - (callback ? 1 : 0);
        if (count === 1) {
            return any.validate(value, callback);
        }

        var options = count === 3 ? arguments[2] : {};
        var schema = root.compile(arguments[1]);

        return schema._validateWithOptions(value, options, callback);
    };

    root.describe = function () {

        var schema = arguments.length ? root.compile(arguments[0]) : any;
        return schema.describe();
    };

    root.compile = function (schema) {

        try {
            return Cast.schema(schema);
        }
        catch (err) {
            if (err.hasOwnProperty('path')) {
                err.message += '(' + err.path + ')';
            }
            throw err;
        }
    };

    root.assert = function (value, schema, message) {

        root.attempt(value, schema, message);
    };

    root.attempt = function (value, schema, message) {

        var result = root.validate(value, schema);
        var error = result.error;
        if (error) {
            if (!message) {
                error.message = error.annotate();
                throw error;
            }

            if (!(message instanceof Error)) {
                error.message = message + ' ' + error.annotate();
                throw error;
            }

            throw message;
        }

        return result.value;
    };

    return root;
};

module.exports = internals.root();


text:
Joda-Convert is intended for one simple task -
Converting objects to and from strings.
This is a common problem, particularly when communicating over textual protocols like XML or JSON.

## Basic usage

Using Joda-Convert is easy at the simplest level.
The main access is via the class `StringConvert`.

The easiest way to use the conversion is via the global constant:

```
// conversion to a String
TimeZone zone = ...
String str = StringConvert.INSTANCE.convertToString(zone);

// conversion from a String
TimeZone zone = StringConvert.INSTANCE.convertFromString(TimeZone.class, str);
```

In both cases, if the input is `null` then the output will also be `null`.

The global constant is quick and easy to use, but is shared between all users in the `ClassLoader`.
It also cannot be extended.

The alternative approach is to instantiate your own instance of `StringConvert`.
This would normally be stored in your own static variable, or made available as needed by dependency injection.
This may be updated by registering your own converters.

## Converters

Each instance of `StringConvert`, including the global singleton, includes a standard set of JDK-based converters.
These cover all the standard JDK types for which conversion to and from a string is sensible.
The set also includes JSR-310 types, but these are optional and loaded by reflection.
The system will run without any dependency.

The JDK conversions are generally obvious. The types are as follows:

* String
* CharSequence
* StringBuffer
* StringBuilder
* long and Long
* int and Integer
* short and Short
* char and Character
* byte and Byte
* double and Double
* float and Float
* boolean and Boolean - 'true' or 'false'
* byte[] - using Base-64 encoding
* char[]
* BigInteger
* BigDecimal
* AtomicLong
* AtomicInteger
* AtomicBoolean - 'true' or 'false'
* Locale - separated by underscores, en_GB_VARIANT
* Class - using the class name, using the rename handler
* Package - using the package name
* Currency - using the three letter code
* TimeZone - using the ID
* UUID - using the toString() form
* URL - using the toString() form
* URI - using the toString() form
* InetAddress - using the host address
* File - using the toString() form
* Date - yyyy-MM-dd'T'HH:mm:ss.SSSZ
* Calendar - yyyy-MM-dd'T'HH:mm:ss.SSSZ, Gregorian only
* Instant
* Duration
* LocalDate
* LocalTime
* LocalDateTime
* OffsetTime
* OffsetDateTime
* ZonedDateTime
* Year
* YearMonth
* MonthDay
* Period
* ZoneOffset
* ZoneId
* Enum subclasses - using name(), annotations can override

Note that the JSR-310 date types are supported in three different package namespaces -
'java.time', 'javax.time' and 'org.threeten.bp'.

Each `StringConvert` instance, other than the global singleton, may have additional converters registered manually.
Each converter implements the `StringConverter` interface, which is self explanatory.

Converters may also be manually added by method name.
This is equivalent to using annotations, but suitable when you don't own the code to add them.
See `StringConvert.registerMethods` and `StringConvert.registerMethodConstructor`.

## Factories

In addition to manual registration of individual converters, each instance of `StringConvert`
has a list of factories to use. The `StringConverterFactory` interface defines the factory.
This allows either bulk registration or dynamic lookup of converters.

A factory is provided to allow numeric arrays to be converted to/from a comma separated list.
A separate factory handles numeric object arrays.
Another factory is provided to allow boolean arrays to be converted to/from a string such as 'TTFFT'.
Again, a separate factory handles boolean object arrays.
Primitive byte and char arrays are handled by default, but the primitive object arrays are
handled via their own factories.

These extra factories must be manually registered, unless the `StringConvert.create()`
static method is used, which defines an "extended" converter with the factories included.

## Annotation based conversion

If there is no registered converter for a type, then a search by annotation is performed.
This will search for the `ToString` and `FromString` annotation on the type.
These annotations will indicate which method should be called to perform the conversion.

```
public class Distance {

  @FromString
  public static Distance parse(String str) { ... }

  @ToString
  public String getStandardOutput() { ... }

}
```

To be valid, the class must contain one `ToString` annotation and one `FromString` annotation.
The `ToString` annotation must be an instance method taking no parameters and returning a String.
The `FromString` annotation must be either a static method or a constructor taking a String parameter and
returning the correct type.
If the annotations are not found on the target class, then superclasses are searched, followed by immediate parent interfaces.

Sometimes, you want to provide to/from string conversions for interfaces.
In Java SE 8 this can be done using static methods on interfaces.
However in earlier versions, a separate "factory" class is necessary.
This can also be annotated:

```
@FromStringFactory(factory = DistanceFactory.class)
public interface Distance {

  @ToString
  String standardFormat();

}

public class Metres implements Distance {

  @Override
  public String standardFormat() { ... }

}

public class DistanceFactory {

  @FromString
  public static Distance parseDistance(String str) { ... }

}
```

The `FromStringFactory` annotation points at the factory class that will provide the factory method.
Although intended for use with interfaces, it can also be used on the target class or any superclass.
Note that only the immediate parent interfaces of a class will be searched.

The effective type of the converter in use is the type that declares the `FromString`
or `FromStringFactory` annotation.
This can be used by serialization systems to determine the best type of the value to send.
One use case is to declare annotations on a public superclass and have all the subclasses be package scoped.
Using the effective type, the package scoped subclasses remain out of the serialized form and
off the public API.

## Rename handler

Most large bodies of code will end up renaming classes and enum constants at some point.
The `RenameHandler` class provides a convenient central place to track this.

If the `RenameHandler` is setup with details of a rename, then an old class name
or enum constant can be read in and will be automatically converted.

## Rationale

The concept is that other open source libraries, as well as your application code, will implement these two annotations.
For open source projects, a key point is that adding the annotations is a compile-time only event.
The Joda-Convert jar file is not needed by your users unless they want to use conversion.
If they don't want to use Joda-Convert then the annotations are effectively ignored.

Joda-Time v2.0 and Joda-Money contain these annotations.
In both cases, the dependency is optional at runtime for users of the projects.
(Note that Scala does not honour the optional behaviour.)


text:
require 'spec_helper'

describe KathyLee::Attributes do

  describe "method_missing" do

    it "should set the attributes" do
      at = KathyLee::Attributes.new(:foo => 'bar') do
        name 'Mark Bates'
      end
      res = at.process
      res.should == {:foo => 'bar', :name => 'Mark Bates'}
    end

  end

end


text:
package resource

import (
	"k8s.io/api/core/v1"
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/fields"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
)

type PodResourceKind struct {
}

func (rk PodResourceKind) GetKind() string {
	return "pods"
}

func (rk PodResourceKind) GetName(obj interface{}) string {
	return obj.(*v1.Pod).GetName()
}

func (rk PodResourceKind) GetStatus(obj interface{}) interface{} {
	return obj.(*v1.Pod).Status
}

func (rk PodResourceKind) MakeRuntimeObject() runtime.Object {
	return &v1.Pod{}
}

func (rk PodResourceKind) MakeWarmUpRuntimeObject() runtime.Object {
	return &v1.Pod{ObjectMeta: meta_v1.ObjectMeta{
		Name:      "deleteme",
		Namespace: v1.NamespaceDefault,
	}}
}

func (rk PodResourceKind) NewListWatchFromClient(clientset *kubernetes.Clientset, namespace string, flds fields.Selector) *cache.ListWatch {
	return cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), rk.GetKind(), namespace, flds)
}


text:
/*
 * DO NOT EDIT THIS CODE BY HAND! It has been generated with jsvcgen.
 */
package com.solidfire.element.api;

import com.solidfire.gson.Gson;
import com.solidfire.core.client.Attributes;
import com.solidfire.gson.annotations.SerializedName;
import com.solidfire.core.annotation.Since;
import com.solidfire.core.javautil.Optional;
import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Objects;

/**
 * ListVirtualVolumeBindingsRequest
 * ListVirtualVolumeBindings returns a list of all virtual volumes in the cluster that are bound to protocol endpoints.
 **/

public class ListVirtualVolumeBindingsRequest implements Serializable {

    public static final long serialVersionUID = 2496874943646211924L;
    @SerializedName("virtualVolumeBindingIDs") private Optional<Long[]> virtualVolumeBindingIDs;
    // empty constructor
    @Since("7.0")
    public ListVirtualVolumeBindingsRequest() {}

    // parameterized constructor
    @Since("7.0")
    public ListVirtualVolumeBindingsRequest(
        Optional<Long[]> virtualVolumeBindingIDs
    )
    {
        this.virtualVolumeBindingIDs = (virtualVolumeBindingIDs == null) ? Optional.<Long[]>empty() : virtualVolumeBindingIDs;
    }

    /**
     * A list of virtual volume binding IDs for which to retrieve information. If you omit this parameter, the method returns information about all virtual volume bindings.
     **/
    public Optional<Long[]> getVirtualVolumeBindingIDs() { return this.virtualVolumeBindingIDs; }

    public void setVirtualVolumeBindingIDs(Optional<Long[]> virtualVolumeBindingIDs) {
        this.virtualVolumeBindingIDs = (virtualVolumeBindingIDs == null) ? Optional.<Long[]>empty() : virtualVolumeBindingIDs;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        ListVirtualVolumeBindingsRequest that = (ListVirtualVolumeBindingsRequest) o;

        return
            Objects.equals(virtualVolumeBindingIDs, that.virtualVolumeBindingIDs);
    }

    @Override
    public int hashCode() {
        return Objects.hash( virtualVolumeBindingIDs );
    }

    public java.util.Map<String, Object> toMap() {
        java.util.Map<String, Object> map = new HashMap<>();
        map.put("virtualVolumeBindingIDs", virtualVolumeBindingIDs);
        return map;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        Gson gson = new Gson();
        sb.append( "{ " );

        if(null != virtualVolumeBindingIDs && virtualVolumeBindingIDs.isPresent()){
            sb.append(" virtualVolumeBindingIDs : ").append(gson.toJson(virtualVolumeBindingIDs)).append(",");
        }
        else{
            sb.append(" virtualVolumeBindingIDs : ").append("null").append(",");
        }
        sb.append( " }" );

        if(sb.lastIndexOf(", }") != -1)
            sb.deleteCharAt(sb.lastIndexOf(", }"));

        return sb.toString();
    }

    public static Builder builder() {
        return new Builder();
    }

    public final Builder asBuilder() {
        return new Builder().buildFrom(this);
    }

    public static class Builder {
        private Optional<Long[]> virtualVolumeBindingIDs;

        private Builder() { }

        public ListVirtualVolumeBindingsRequest build() {
            return new ListVirtualVolumeBindingsRequest (
                         this.virtualVolumeBindingIDs);
        }

        private ListVirtualVolumeBindingsRequest.Builder buildFrom(final ListVirtualVolumeBindingsRequest req) {
            this.virtualVolumeBindingIDs = req.virtualVolumeBindingIDs;

            return this;
        }

        public ListVirtualVolumeBindingsRequest.Builder optionalVirtualVolumeBindingIDs(final Long[] virtualVolumeBindingIDs) {
            this.virtualVolumeBindingIDs = (virtualVolumeBindingIDs == null) ? Optional.<Long[]>empty() : Optional.of(virtualVolumeBindingIDs);
            return this;
        }

    }
}


text:
RedmineApi::RedmineApi(const std::string& serverUrl, const std::string& apiKey)
		: _apiKey(apiKey)
		, _session(serverUrl
				   , Poco::Net::HTTPSClientSession::HTTPS_PORT
				   , Poco::Net::Context::Ptr(new Poco::Net::Context(Poco::Net::Context::CLIENT_USE, "", "", ""
																	, Poco::Net::Context::VERIFY_NONE, 9, false
																	, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH")))
{
}

std::vector<WorkActivity> RedmineApi::getTimeEntryActivities()
{
	Enumerations api;
	auto request = api.requestTimeEntryActivities(_apiKey);

	try
	{
		_session.sendRequest(*request);

		Poco::Net::HTTPResponse response;
		auto& body = _session.receiveResponse(response);

		return api.processTimeEntryActivities(response, body);
	}
	catch (const std::exception& ex)
	{
		logException(ex);
		throw;
	}
}

void RedmineApi::logException(const std::exception& ex)
{
	//TODO later
	//		Reporter reporter;
	//		reporter.handle(Fail::where(__FILE__, __func__, __LINE__), urlBuilder.build() + "\n" + ex.what()
	//						, connection.get());
}

bool RedmineApi::logTime(const TimeEntry& timeEntry)
{
	TimeEntries api;
	auto request = api.requestLogTime(_apiKey);
	try
	{
		api.logTimeBody(_session.sendRequest(*request), timeEntry);

		Poco::Net::HTTPResponse response;
		auto& body = _session.receiveResponse(response);

		request->write(std::cout);
		response.write(std::cout);

		return api.processLogTime(response, body);
	}
	catch (const std::exception& ex)
	{
		logException(ex);
		throw;
	}
}


text:
module Seory
  class ControllerDouble
    def initialize(slug, params = {}, &block)
      @__slug   = slug
      @params = params

      instance_eval(&block) if block
    end

    def controller_name
      controller_path.split('/').last
    end

    def controller_path
      @__slug.split('#').first
    end

    def action_name
      @__slug.split('#').last
    end

    def params
      @params.merge(controller: controller_path, action: action_name)
    end

    def view_assigns
      instance_variables.each_with_object({}) do |ivar, assigns|
        name = ivar.to_s
        next if name.start_with?('@__') || name == '@params'

        assigns[name[1..-1]] = instance_variable_get(ivar)
      end
    end
  end
end


text:
namespace Fonet.Pdf
{
    /// <summary>
    ///     A Type 0 font is a composite font whose glyphs are obtained from a
    ///     font like object called a CIDFont (a descendant font).
    /// </summary>
    /// <remarks>
    ///     All versions of the PDF specification up to and including version 1.4
    ///     only support a single descendant font.
    /// </remarks>
    public class PdfType0Font : PdfFont
    {
        public PdfType0Font(PdfObjectId objectId, string fontName, string baseFont)
            : base(fontName, objectId)
        {
            this[PdfName.Names.Subtype] = PdfName.Names.Type0;
            this[PdfName.Names.BaseFont] = new PdfName(baseFont);
        }

        /// <summary>
        ///     Sets the stream containing a CMap that maps character codes to
        ///     unicode values.
        /// </summary>
        public PdfCMap ToUnicode
        {
            set { this[PdfName.Names.ToUnicode] = value.GetReference(); }
        }

        /// <summary>
        ///     Sets the descendant font.
        /// </summary>
        public PdfCIDFont Descendant
        {
            set
            {
                PdfArray array = new PdfArray();
                array.Add(value.GetReference());

                this[PdfName.Names.DescendantFonts] = array;
            }
        }

        /// <summary>
        ///     Sets a value representing the character encoding.
        /// </summary>
        public PdfName Encoding
        {
            set { this[PdfName.Names.Encoding] = value; }
        }
    }
}


text:
package org.opencds.terminology;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.omg.dss.DSSRuntimeExceptionFault;
import org.opencds.common.config.OpencdsConfigurator;
import org.opencds.common.utilities.DateUtility;
import org.opencds.common.utilities.StringToArrayUtility;
import org.opencds.knowledgeRepository.SimpleKnowledgeRepository;
import org.opencds.terminology.EnumerationUtility;

/**
 * GuvnorConceptNameFunctionCreator creates a function for looking up OpenCDS concept names within Guvnor.
 *
 * The main method results can be copied directly into Guvnor as a function.
 *
 * @author Kensaku Kawamoto
 *
 */
public class GuvnorConceptNameLookupFunctionCreator {

	public static void main(String[] args) throws DSSRuntimeExceptionFault
	{
		// added line below to use automatic configuration based on config file des 2012-01-10
//		new OpencdsConfigurator();
		// revised to configure SimpleKnowledgeRepository correctly des 2012-07-05
        OpencdsConfigurator oConfig = new OpencdsConfigurator();  		// initializes the configurator.
        SimpleKnowledgeRepository.setFullPathToKRData(oConfig.getKrFullPath());	// initializes the KnowledgeRepository

	      EnumerationUtility utility = new EnumerationUtility();
	      Map<String, List<String>> enums = utility.loadEnumerations();

	      System.out.println("Copy the content below into the Drools Guvnor Functions entry.");
	      System.out.println();
	      System.out.println();
	      System.out.println();
	      String startTime = DateUtility.getInstance().getDateAsString(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
	      System.out.println("// " + startTime + " Lookups generated from org.opencds.terminology.GuvnorConceptNameLookupFunctionCreator.  Taking this approach to enable enumeration manipulation without server restart.");
	      System.out.println();

	      ArrayList<String> keys = new ArrayList<String>(enums.keySet());
	      HashSet<String> conceptToDisplayNameSet = new HashSet<String>();
	      for (String key : keys)
	      {
	    	  List<String> enumContents = enums.get(key);
	    	  if (enumContents.size() > 0)
	    	  {
	    		  for (int k = 0; k < enumContents.size(); k++)
	    		  {
	    			  conceptToDisplayNameSet.add(enumContents.get(k));
	    		  }
	    	  }
	      }
	      ArrayList<String> conceptToDisplayNameList = new ArrayList<String>(conceptToDisplayNameSet);
	      Collections.sort(conceptToDisplayNameList);

	      System.out.println("function String GetOpenCDSConceptName(String conceptCode)");
	      System.out.println("{");
	      System.out.println("    HashMap<String, String> openCdsConceptCodeToName = new HashMap<String, String>();");
	      for (String conceptToDisplayName : conceptToDisplayNameList)
	      {
	    	  if (conceptToDisplayName.startsWith("C"))
	    	  {
		    	  ArrayList<String> components = StringToArrayUtility.getInstance().getRegularArrayFromString(conceptToDisplayName, "=");
		    	  String conceptCode = components.get(0);
		    	  String displayName = components.get(1);
		    	  System.out.println("    openCdsConceptCodeToName.put(\"" + conceptCode + "\", \"" + displayName + "\");");
	    	  }
	      }
	      System.out.println("    String name = openCdsConceptCodeToName.get(conceptCode);");
	      System.out.println("    if (name == null)");
	      System.out.println("    {  name = \"\"; } ");
	      System.out.println("    return name;");
	      System.out.println("}");
	}
}


text:
TEST_GROUP(i8254_test);

static volatile uint32_t testVar;

static int callback(struct regs *r, void *p)
{
    testVar++;
    return 0;
}

TEST_SETUP(i8254_test)
{
    testVar = 0;
    register_interrupt_handler(32, &callback, (void*)0xDEADBEEF);
}
TEST_TEAR_DOWN(i8254_test)
{
    unregister_interrupt_handler(32, &callback, (void*)0xDEADBEEF);
}

TEST(i8254_test, didTimePass)
{
    while(testVar < 200);
    TEST_ASSERT(testVar != 0); // Make sure time has passed
}

TEST(i8254_test, updatedTimestamp)
{
    uint64_t ts = get_timestamp();
    while(testVar < 200);
    TEST_ASSERT(get_timestamp() > ts);
}


text:
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var debug = require('debug');
var Promise = require('bluebird');
var constants = require('../constants');
var errors = constants.errors;
var blueprintServiceDebug = debug('app:flux:services:BlueprintService');
var ServiceResponseParser = (function () {
    function ServiceResponseParser() {
    }
    // parse server response
    ServiceResponseParser.prototype.defaultResponseHandler = function (resolve, reject, err, res) {
        if (err) {
            return reject(this.parseError(err));
        }
        var parsed = this.parseResponse(res);
        if (parsed.hasError) {
            return reject(parsed);
        }
        return resolve(parsed);
    };
    // parse query
    ServiceResponseParser.prototype.parseQuery = function (query) {
        var parsedQuery = {}, qKeys = Object.keys(query || {});
        qKeys.forEach(function (searchKey) {
            var searchValue = query[searchKey];
            if (typeof searchValue === 'object') {
                parsedQuery[searchKey] = JSON.stringify(searchValue);
            }
            else {
                parsedQuery[searchKey] = searchValue;
            }
        });
        return parsedQuery;
    };
    // parse error
    ServiceResponseParser.prototype.parseError = function (err) {
        return err;
    };
    // parse server response
    ServiceResponseParser.prototype.parseResponse = function (response) {
        var parsed = {};
        // success
        if (response.status >= 200 && response.status < 300) {
            parsed.data = response.body;
            parsed.hasError = false;
            parsed.status = response.status;
            return parsed;
        }
        ;
        // not found
        if (response.notFound) {
            parsed = response.body || errors['E_NOT_FOUND'];
            parsed.hasError = true;
            parsed.summary = !response.body && response.text;
            return parsed;
        }
        // bad request
        if (response.badRequest) {
            parsed = response.body || errors['E_BAD_REQUEST'];
            parsed.hasError = true;
            parsed.summary = !response.body && response.text;
            return parsed;
        }
        // internal error
        if (response.status === 500) {
            parsed = response.body || errors['E_INTERNAL'];
            parsed.hasError = true;
            parsed.summary = !response.body && response.text;
            return parsed;
        }
        parsed = response.body || errors['E_UNKNOWN'];
        parsed.hasError = true;
        // unknown reasons
        return parsed;
    };
    return ServiceResponseParser;
})();
exports.ServiceResponseParser = ServiceResponseParser;
var BlueprintService = (function (_super) {
    __extends(BlueprintService, _super);
    function BlueprintService(opts) {
        _super.call(this);
        if (opts.resourceName === undefined) {
            throw new TypeError('Required resourceName is missing! The resourceName is required when making server requests.');
        }
        this.resourceName = opts.resourceName.toLowerCase();
    }
    BlueprintService.prototype.getResourceName = function () {
        return this.resourceName;
    };
    BlueprintService.prototype.getPK = function () {
        return 'id';
    };
    BlueprintService.prototype.create = function (request, data, query) {
        var _this = this;
        var parsedQuery = this.parseQuery(query);
        return new Promise(function (resolve, reject) {
            request('POST', _this.getResourceName()).send(data).query(parsedQuery).end(_this.defaultResponseHandler.bind(_this, resolve, reject));
        });
    };
    BlueprintService.prototype.update = function (request, resourceId, data, query) {
        var _this = this;
        var uri = this.getResourceName() + "/" + resourceId, parsedQuery = this.parseQuery(query);
        return new Promise(function (resolve, reject) {
            request('PUT', uri).send(data).query(parsedQuery).end(_this.defaultResponseHandler.bind(_this, resolve, reject));
        });
    };
    // alias Update
    BlueprintService.prototype.batch = function (request, resourceId, data, query) {
        return this.update(request, resourceId, data, query);
    };
    BlueprintService.prototype.delete = function (request, resourceId, query) {
        var _this = this;
        var uri = this.getResourceName() + "/" + resourceId, parsedQuery = this.parseQuery(query);
        return new Promise(function (resolve, reject) {
            request('DELETE', uri).query(parsedQuery).end(_this.defaultResponseHandler.bind(_this, resolve, reject));
        });
    };
    BlueprintService.prototype.getById = function (request, resourceId, query) {
        var _this = this;
        var uri = this.getResourceName() + "/" + resourceId, parsedQuery = this.parseQuery(query);
        return new Promise(function (resolve, reject) {
            request('GET', uri).query(query).end(_this.defaultResponseHandler.bind(_this, resolve, reject));
        });
    };
    BlueprintService.prototype.getBy = function (request, fields, query) {
        return this.find(request, fields, query);
    };
    BlueprintService.prototype.find = function (request, criteria, query) {
        var _this = this;
        if (criteria === void 0) { criteria = {}; }
        if (query === void 0) { query = {}; }
        var complexCriteria = query;
        complexCriteria.where = criteria;
        var parsedQuery = this.parseQuery(complexCriteria);
        return new Promise(function (resolve, reject) {
            request("GET", _this.getResourceName())
                .query(parsedQuery)
                .end(_this.defaultResponseHandler.bind(_this, resolve, reject));
        });
    };
    BlueprintService.prototype.addTo = function (request, resourceId, subResource, subResourceData, query) {
        var _this = this;
        var uri = this.getResourceName() + "/" + resourceId + "/" + subResource, parsedQuery = this.parseQuery(query);
        return new Promise(function (resolve, reject) {
            request('POST', uri).send(subResourceData).query(parsedQuery).end(_this.defaultResponseHandler.bind(_this, resolve, reject));
        });
    };
    BlueprintService.prototype.link = function (request, resourceId, subResource, subResourceId, query) {
        var _this = this;
        var uri = this.getResourceName() + "/" + resourceId + "/" + subResource + "/" + subResourceId, parsedQuery = this.parseQuery(query);
        return new Promise(function (resolve, reject) {
            request('GET', uri).query(parsedQuery).end(_this.defaultResponseHandler.bind(_this, resolve, reject));
        });
    };
    BlueprintService.prototype.unLink = function (request, resourceId, subResource, subResourceId, query) {
        var _this = this;
        var uri = this.getResourceName() + "/" + resourceId + "/" + subResource + "/" + subResourceId, parsedQuery = this.parseQuery(query);
        return new Promise(function (resolve, reject) {
            request('DELETE', uri).query(parsedQuery).end(_this.defaultResponseHandler.bind(_this, resolve, reject));
        });
    };
    return BlueprintService;
})(ServiceResponseParser);
exports.BlueprintService = BlueprintService;
//# sourceMappingURL=BlueprintService.js.map


text:
using namespace llvm;
using namespace object;
using namespace ELF;

namespace {
class X86_64ELFRelocationInfo : public MCRelocationInfo {
public:
  X86_64ELFRelocationInfo(MCContext &Ctx) : MCRelocationInfo(Ctx) {}

  const MCExpr *createExprForRelocation(RelocationRef Rel) {
    uint64_t RelType; Rel.getType(RelType);
    symbol_iterator SymI = Rel.getSymbol();

    StringRef SymName; SymI->getName(SymName);
    uint64_t  SymAddr; SymI->getAddress(SymAddr);
    uint64_t  SymSize; SymI->getSize(SymSize);
    int64_t  Addend;  getELFRelocationAddend(Rel, Addend);

    MCSymbol *Sym = Ctx.GetOrCreateSymbol(SymName);
    // FIXME: check that the value is actually the same.
    if (Sym->isVariable() == false)
      Sym->setVariableValue(MCConstantExpr::Create(SymAddr, Ctx));

    const MCExpr *Expr = 0;
    // If hasAddend is true, then we need to add Addend (r_addend) to Expr.
    bool hasAddend = false;

    // The AMD64 SysV ABI says:
    // A: the addend used to compute the value of the relocatable field.
    // B: the base address at which a shared object has been loaded into memory
    //    during execution. Generally, a shared object is built with a 0 base
    //    virtual address, but the execution address will be different.
    // G: the offset into the global offset table at which the relocation
    //    entry's symbol will reside during execution.
    // GOT: the address of the global offset table.
    // L: the place (section offset or address) of the Procedure Linkage Table
    //    entry for a symbol.
    // P: the place (section offset or address) of the storage unit being
    //    relocated (computed using r_offset).
    // S: the value of the symbol whose index resides in the relocation entry.
    // Z: the size of the symbol whose index resides in the relocation entry.

    switch(RelType) {
    case R_X86_64_NONE:
    case R_X86_64_COPY:
      // none
      break;
    case R_X86_64_64:
    case R_X86_64_16:
    case R_X86_64_8:
      // S + A
    case R_X86_64_32:
    case R_X86_64_32S:
      // S + A (We don't care about the result not fitting in 32 bits.)
    case R_X86_64_PC32:
    case R_X86_64_PC16:
    case R_X86_64_PC8:
    case R_X86_64_PC64:
      // S + A - P (P/pcrel is implicit)
      hasAddend = true;
      Expr = MCSymbolRefExpr::Create(Sym, Ctx);
      break;
    case R_X86_64_GOT32:
    case R_X86_64_GOT64:
    case R_X86_64_GOTPC32:
    case R_X86_64_GOTPC64:
    case R_X86_64_GOTPLT64:
      // G + A
      hasAddend = true;
      Expr = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_GOT, Ctx);
      break;
    case R_X86_64_PLT32:
      // L + A - P -> S@PLT + A
      hasAddend = true;
      Expr = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_PLT, Ctx);
      break;
    case R_X86_64_GLOB_DAT:
    case R_X86_64_JUMP_SLOT:
      // S
      Expr = MCSymbolRefExpr::Create(Sym, Ctx);
      break;
    case R_X86_64_GOTPCREL:
    case R_X86_64_GOTPCREL64:
      // G + GOT + A - P -> S@GOTPCREL + A
      hasAddend = true;
      Expr = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_GOTPCREL, Ctx);
      break;
    case R_X86_64_GOTOFF64:
      // S + A - GOT
      Expr = MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_GOTOFF, Ctx);
      break;
    case R_X86_64_PLTOFF64:
      // L + A - GOT
      break;
    case R_X86_64_SIZE32:
    case R_X86_64_SIZE64:
      // Z + A
      Expr = MCConstantExpr::Create(SymSize, Ctx);
      break;
    default:
      Expr = MCSymbolRefExpr::Create(Sym, Ctx);
      break;
    }
    if (Expr && hasAddend && Addend != 0)
      Expr = MCBinaryExpr::CreateAdd(Expr,
                                     MCConstantExpr::Create(Addend, Ctx),
                                     Ctx);
    return Expr;
  }
};
} // End unnamed namespace

/// createX86ELFRelocationInfo - Construct an X86 Mach-O RelocationInfo.
MCRelocationInfo *llvm::createX86_64ELFRelocationInfo(MCContext &Ctx) {
  // We only handle x86-64 for now.
  return new X86_64ELFRelocationInfo(Ctx);
}


text: A minimal rainloop container for Docker, designed for having a seperate web server somewhere.


text:
<!DOCTYPE html>

    <meta name="description" content="AngularJS directive to keep only numbers when typing in input fields">
    <meta name="keywords" content="AngularJS, directive, input, numbers">
    <meta name="author" content="Alexandru Costin Dumitru (AlexCD)">
    <meta charset="UTF-8">
    <title>AngularInputOnlyNumbers</title>

    <link rel="stylesheet" type="text/css" href="css/styles.css" />

    <form name="theForm">

Min: 10

        <input type="text" ng-model="model" min="10" max="100" input-only-numbers />

Max: 100

    </form>

        Invalid range

Valid range


text:
package testing

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"time"

	"github.com/fullstorydev/hauser/warehouse"
)

type MockStorage struct {
	Syncs         []time.Time
	UploadedFiles map[string][]byte
	DeletedFiles  []string
	FilePrefix    string
}

var _ warehouse.Storage = (*MockStorage)(nil)

func NewMockStorage() *MockStorage {
	return &MockStorage{
		Syncs:         nil,
		UploadedFiles: make(map[string][]byte),
		DeletedFiles:  nil,
		FilePrefix:    "prefix/",
	}
}

func (m *MockStorage) LastSyncPoint(_ context.Context) (time.Time, error) {
	var max time.Time
	for i, s := range m.Syncs {
		if i == 0 || s.After(max) {
			max = s
		}
	}
	return max, nil
}

func (m *MockStorage) SaveSyncPoint(ctx context.Context, endTime time.Time) error {
	m.Syncs = append(m.Syncs, endTime)
	return nil
}

func (m *MockStorage) SaveFile(_ context.Context, name string, reader io.Reader) (string, error) {
	data, err := ioutil.ReadAll(reader)
	if err != nil {
		return "", err
	}
	m.UploadedFiles[name] = data
	return m.GetFileReference(name), nil
}

func (m *MockStorage) ReadFile(_ context.Context, name string) (io.Reader, error) {
	if data, ok := m.UploadedFiles[name]; !ok {
		return nil, warehouse.ErrFileNotFound
	} else {
		return bytes.NewReader(data), nil
	}
}

func (m *MockStorage) DeleteFile(_ context.Context, path string) error {
	m.DeletedFiles = append(m.DeletedFiles, path)
	return nil
}

func (m *MockStorage) GetFileReference(name string) string {
	return fmt.Sprintf("mock://%s", name)
}

func (m *MockStorage) GetFilePrefix() string {
	return m.FilePrefix
}


text:
title = "Ironclad"

tagline = "A command line password manager."

version = "Version 2.3.0"