text:
#include "ParaNdis-Oid.h"
#include "ParaNdis6.h"
#include "kdebugprint.h"
#include "ParaNdis_DebugHistory.h"
#include "netkvmmof.h"
#include "Trace.h"
#ifdef NETKVM_WPP_ENABLED
#include "ParaNdis6-Oid.tmh"
#endif

static NDIS_IO_WORKITEM_FUNCTION OnSetPowerWorkItem;

#define OIDENTRY(oid, el, xfl, xokl, flags) \
{ oid, el, xfl, xokl, flags, NULL }
#define OIDENTRYPROC(oid, el, xfl, xokl, flags, setproc) \
{ oid, el, xfl, xokl, flags, setproc }

/**********************************************************
Just fail the request for unsupported OID
Parameters:
    context
    tOidDesc *pOid      descriptor of OID request
Return value:
    whatever
***********************************************************/
static NDIS_STATUS OnSetInterruptModeration(PARANDIS_ADAPTER *pContext, tOidDesc *pOid)
{
    UNREFERENCED_PARAMETER(pContext);
    UNREFERENCED_PARAMETER(pOid);

    return  NDIS_STATUS_INVALID_DATA;
}

static NDIS_STATUS OnSetOffloadParameters(PARANDIS_ADAPTER *pContext, tOidDesc *pOid);
static NDIS_STATUS OnSetOffloadEncapsulation(PARANDIS_ADAPTER *pContext, tOidDesc *pOid);
static NDIS_STATUS OnSetLinkParameters(PARANDIS_ADAPTER *pContext, tOidDesc *pOid);
static NDIS_STATUS OnSetVendorSpecific1(PARANDIS_ADAPTER *pContext, tOidDesc *pOid);
static NDIS_STATUS OnSetVendorSpecific2(PARANDIS_ADAPTER *pContext, tOidDesc *pOid);

#define OID_VENDOR_1                    0xff010201
#define OID_VENDOR_2                    0xff010202

#if PARANDIS_SUPPORT_RSS

static NDIS_STATUS RSSSetParameters(PARANDIS_ADAPTER *pContext, tOidDesc *pOid)
{
    NDIS_STATUS status;

    if (!pContext->bRSSOffloadSupported)
        return NDIS_STATUS_NOT_SUPPORTED;

    CNdisPassiveWriteAutoLock autoLock(pContext->RSSParameters.rwLock);

    status = ParaNdis6_RSSSetParameters(&pContext->RSSParameters,
                                        (NDIS_RECEIVE_SCALE_PARAMETERS*) pOid->InformationBuffer,
                                        pOid->InformationBufferLength,
                                        pOid->pBytesRead,
                                        pContext->MiniportHandle);
    ParaNdis_ResetRxClassification(pContext);
    if (status != NDIS_STATUS_SUCCESS)
    {
        DPrintf(0, "[%s] - RSS parameters setting failed\n", __FUNCTION__);
    }

    if (status == NDIS_STATUS_SUCCESS)
    {
        status = ParaNdis_SetupRSSQueueMap(pContext);
    }

    if (status != NDIS_STATUS_SUCCESS)
    {
        DPrintf(0, "[%s] - RSS to queue mapping setup failed\n", __FUNCTION__);
    }

    return status;
}

static NDIS_STATUS RSSSetReceiveHash(   PARANDIS_ADAPTER *pContext, tOidDesc *pOid)
{
    NDIS_STATUS status;

    if (!pContext->bRSSOffloadSupported)
        return NDIS_STATUS_NOT_SUPPORTED;

    status = ParaNdis6_RSSSetReceiveHash(   &pContext->RSSParameters,
                                        (NDIS_RECEIVE_HASH_PARAMETERS*) pOid->InformationBuffer,
                                        pOid->InformationBufferLength,
                                        pOid->pBytesRead);

    ParaNdis_ResetRxClassification(pContext);

    return status;
}

#endif

/**********************************************************
Structure defining how to support each OID
***********************************************************/
static const tOidWhatToDo OidsDB[] =
{
//                                              i f ok flags        set proc
OIDENTRY(OID_GEN_SUPPORTED_LIST,                2,2,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_HARDWARE_STATUS,               2,0,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_MEDIA_SUPPORTED,               2,0,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_MEDIA_IN_USE,                  2,0,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_MAXIMUM_LOOKAHEAD,             2,0,4, ohfQuery         ),
OIDENTRY(OID_GEN_MAXIMUM_FRAME_SIZE,            2,0,4, ohfQuery         ),
OIDENTRY(OID_GEN_TRANSMIT_BUFFER_SPACE,         2,0,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_RECEIVE_BUFFER_SPACE,          2,0,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_TRANSMIT_BLOCK_SIZE,           2,0,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_RECEIVE_BLOCK_SIZE,            2,0,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_VENDOR_ID,                     2,0,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_VENDOR_DESCRIPTION,            2,2,4, ohfQueryStat     ),
OIDENTRYPROC(OID_GEN_CURRENT_PACKET_FILTER,     2,0,4, ohfQuerySet, ParaNdis_OnSetPacketFilter),
OIDENTRYPROC(OID_GEN_CURRENT_LOOKAHEAD,         2,0,4, ohfQuerySet, ParaNdis_OnSetLookahead),
OIDENTRY(OID_GEN_DRIVER_VERSION,                2,0,4, ohfQuery         ),
OIDENTRY(OID_GEN_MAXIMUM_TOTAL_SIZE,            2,0,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_PROTOCOL_OPTIONS,              2,0,4, 0                ),
OIDENTRY(OID_GEN_MAC_OPTIONS,                   2,0,4, ohfQuery         ),
OIDENTRY(OID_GEN_MAXIMUM_SEND_PACKETS,          2,0,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_VENDOR_DRIVER_VERSION,         2,0,4, ohfQueryStat     ),
OIDENTRY(OID_GEN_SUPPORTED_GUIDS,               2,4,4, ohfQueryStat     ),
OIDENTRYPROC(OID_GEN_NETWORK_LAYER_ADDRESSES,   2,2,4, ohfSet,      ParaNdis_OnOidSetNetworkAddresses),
OIDENTRY(OID_GEN_TRANSPORT_HEADER_OFFSET,       2,4,4, 0                ),
OIDENTRY(OID_GEN_MEDIA_CAPABILITIES,            2,4,4, 0                ),
OIDENTRY(OID_GEN_PHYSICAL_MEDIUM,               2,4,4, 0                ),
OIDENTRY(OID_GEN_XMIT_OK,                       3,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_RCV_OK,                        3,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_XMIT_ERROR,                    2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_RCV_ERROR,                     2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_RCV_NO_BUFFER,                 2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_DIRECTED_BYTES_XMIT,           2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_DIRECTED_FRAMES_XMIT,          2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_MULTICAST_BYTES_XMIT,          2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_MULTICAST_FRAMES_XMIT,         2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_BROADCAST_BYTES_XMIT,          2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_BROADCAST_FRAMES_XMIT,         2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_DIRECTED_BYTES_RCV,            2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_DIRECTED_FRAMES_RCV,           2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_MULTICAST_BYTES_RCV,           2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_MULTICAST_FRAMES_RCV,          2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_BROADCAST_BYTES_RCV,           2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_BROADCAST_FRAMES_RCV,          2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_GEN_RCV_CRC_ERROR,                 2,4,4, 0                ),
OIDENTRY(OID_GEN_TRANSMIT_QUEUE_LENGTH,         2,0,4, ohfQuery         ),
OIDENTRY(OID_GEN_GET_TIME_CAPS,                 2,4,4, 0                ),
OIDENTRY(OID_GEN_GET_NETCARD_TIME,              2,4,4, 0                ),
OIDENTRY(OID_GEN_NETCARD_LOAD,                  2,4,4, 0                ),
OIDENTRY(OID_GEN_DEVICE_PROFILE,                2,4,4, 0                ),
OIDENTRY(OID_GEN_INIT_TIME_MS,                  2,4,4, 0                ),
OIDENTRY(OID_GEN_RESET_COUNTS,                  2,4,4, 0                ),
OIDENTRY(OID_GEN_MEDIA_SENSE_COUNTS,            2,4,4, 0                ),
OIDENTRY(OID_PNP_CAPABILITIES,                  2,0,4, ohfQuery         ),
OIDENTRYPROC(OID_PNP_SET_POWER,                 2,0,4, ohfSet | ohfSetMoreOK, ParaNdis_OnSetPower),
OIDENTRY(OID_PNP_QUERY_POWER,                   2,0,4, ohfQuery         ),
OIDENTRYPROC(OID_PNP_ADD_WAKE_UP_PATTERN,       2,0,4, ohfSet,          ParaNdis_OnAddWakeupPattern),
OIDENTRYPROC(OID_PNP_REMOVE_WAKE_UP_PATTERN,    2,0,4, ohfSet,          ParaNdis_OnRemoveWakeupPattern),
OIDENTRYPROC(OID_PNP_ENABLE_WAKE_UP,            2,0,4, ohfQuerySet,     ParaNdis_OnEnableWakeup),
OIDENTRY(OID_802_3_PERMANENT_ADDRESS,           2,0,4, ohfQueryStat     ),
OIDENTRY(OID_802_3_CURRENT_ADDRESS,             2,0,4, ohfQueryStat     ),
OIDENTRYPROC(OID_802_3_MULTICAST_LIST,          2,0,4, ohfQuerySet,     ParaNdis_OnOidSetMulticastList),
OIDENTRY(OID_802_3_MAXIMUM_LIST_SIZE,           2,0,4, ohfQueryStat     ),
OIDENTRY(OID_802_3_MAC_OPTIONS,                 2,4,4, 0                ),
OIDENTRY(OID_802_3_RCV_ERROR_ALIGNMENT,         2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_802_3_XMIT_ONE_COLLISION,          2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_802_3_XMIT_MORE_COLLISIONS,        2,4,4, ohfQueryStat3264 ),
OIDENTRY(OID_802_3_XMIT_DEFERRED,               2,4,4, 0                ),
OIDENTRY(OID_802_3_XMIT_MAX_COLLISIONS,         2,4,4, 0                ),
OIDENTRY(OID_802_3_RCV_OVERRUN,                 2,4,4, 0                ),
OIDENTRY(OID_802_3_XMIT_UNDERRUN,               2,4,4, 0                ),
OIDENTRY(OID_802_3_XMIT_HEARTBEAT_FAILURE,      2,4,4, 0                ),
OIDENTRY(OID_802_3_XMIT_TIMES_CRS_LOST,         2,4,4, 0                ),
OIDENTRY(OID_802_3_XMIT_LATE_COLLISIONS,        2,4,4, 0                ),
OIDENTRY(OID_GEN_MACHINE_NAME,                  2,4,4, 0                ),
OIDENTRY(OID_GEN_STATISTICS,                    3,4,4, ohfQueryStat     ),
OIDENTRYPROC(OID_GEN_VLAN_ID,                   2,4,4, ohfQueryStat | ohfSet, ParaNdis_OnSetVlanId),
OIDENTRYPROC(OID_GEN_INTERRUPT_MODERATION,      2,4,4, ohfQueryStat | ohfSet, OnSetInterruptModeration),
//Win8 NDIS 6.0 fails without it (Mini6OidsNdisRequests)
OIDENTRYPROC(OID_GEN_LINK_PARAMETERS,           2,0,4, ohfSet, OnSetLinkParameters),
OIDENTRY(OID_IP4_OFFLOAD_STATS,                 4,4,4, 0),
OIDENTRY(OID_IP6_OFFLOAD_STATS,                 4,4,4, 0),
OIDENTRYPROC(OID_TCP_OFFLOAD_PARAMETERS,        0,0,0, ohfSet | ohfSetMoreOK | ohfSetLessOK, OnSetOffloadParameters),
OIDENTRYPROC(OID_OFFLOAD_ENCAPSULATION,         0,0,0, ohfQuerySet, OnSetOffloadEncapsulation),
OIDENTRYPROC(OID_VENDOR_1,                      0,0,0, ohfQueryStat | ohfSet | ohfSetMoreOK, OnSetVendorSpecific1),
OIDENTRYPROC(OID_VENDOR_2,                      0,0,0, ohfQueryStat | ohfSet | ohfSetMoreOK, OnSetVendorSpecific2),

#if PARANDIS_SUPPORT_RSS
    OIDENTRYPROC(OID_GEN_RECEIVE_SCALE_PARAMETERS,  0,0,0, ohfSet | ohfSetMoreOK, RSSSetParameters),
    OIDENTRYPROC(OID_GEN_RECEIVE_HASH,              0,0,0, ohfQuerySet | ohfSetMoreOK, RSSSetReceiveHash),
#endif
#if PARANDIS_SUPPORT_RSC
    OIDENTRY(OID_TCP_RSC_STATISTICS,            3,4,4, ohfQueryStat     ),
#endif

#if NDIS_SUPPORT_NDIS620
// here should be NDIS 6.20 specific OIDs (mostly power management related)
// OID_PM_CURRENT_CAPABILITIES - not requred, supported by NDIS
// OID_PM_PARAMETERS - mandatory
// OID_PM_ADD_WOL_PATTERN - mandatory
// OID_PM_REMOVE_WOL_PATTERN - mandatory
// OID_PM_WOL_PATTERN_LIST - not requred, supported by NDIS
// OID_PM_ADD_PROTOCOL_OFFLOAD - mandatory
// OID_PM_GET_PROTOCOL_OFFLOAD - mandatory
// OID_PM_REMOVE_PROTOCOL_OFFLOAD - mandatory
// OID_PM_PROTOCOL_OFFLOAD_LIST - not required, supported by NDIS
#endif
// last entry, do not remove
OIDENTRY(0,                                     4,4,4, 0),
};

static NDIS_OID SupportedOids[] =
{
        OID_GEN_SUPPORTED_LIST,
        OID_GEN_HARDWARE_STATUS,
        OID_GEN_MEDIA_SUPPORTED,
        OID_GEN_MEDIA_IN_USE,
        OID_GEN_MAXIMUM_LOOKAHEAD,
        OID_GEN_MAXIMUM_FRAME_SIZE,
        OID_GEN_TRANSMIT_BUFFER_SPACE,
        OID_GEN_RECEIVE_BUFFER_SPACE,
        OID_GEN_TRANSMIT_BLOCK_SIZE,
        OID_GEN_RECEIVE_BLOCK_SIZE,
        OID_GEN_VENDOR_ID,
        OID_GEN_VENDOR_DESCRIPTION,
        OID_GEN_VENDOR_DRIVER_VERSION,
        OID_GEN_CURRENT_PACKET_FILTER,
        OID_GEN_CURRENT_LOOKAHEAD,
        OID_GEN_DRIVER_VERSION,
        OID_GEN_MAXIMUM_TOTAL_SIZE,
        OID_GEN_MAC_OPTIONS,
        OID_GEN_MAXIMUM_SEND_PACKETS,
        OID_GEN_LINK_PARAMETERS,
        OID_GEN_NETWORK_LAYER_ADDRESSES,
        OID_GEN_INTERRUPT_MODERATION,
        OID_GEN_XMIT_ERROR,
        OID_GEN_RCV_ERROR,
        OID_GEN_RCV_NO_BUFFER,
        OID_802_3_PERMANENT_ADDRESS,
        OID_802_3_CURRENT_ADDRESS,
        OID_802_3_MULTICAST_LIST,
        OID_802_3_MAXIMUM_LIST_SIZE,
        OID_802_3_RCV_ERROR_ALIGNMENT,
        OID_802_3_XMIT_ONE_COLLISION,
        OID_802_3_XMIT_MORE_COLLISIONS,
        OID_GEN_STATISTICS,
        OID_PNP_CAPABILITIES,
        OID_PNP_SET_POWER,
        OID_PNP_QUERY_POWER,
        OID_GEN_XMIT_OK,
        OID_GEN_RCV_OK,
        OID_GEN_VLAN_ID,
#if NDIS_SUPPORT_NDIS61
// disable WMI custom command on 2008 due to non-filtered NDIS test failure
        OID_GEN_SUPPORTED_GUIDS,
        OID_VENDOR_1,
        OID_VENDOR_2,
#endif
        OID_OFFLOAD_ENCAPSULATION,
        OID_TCP_OFFLOAD_PARAMETERS,
#if PARANDIS_SUPPORT_RSS
        OID_GEN_RECEIVE_SCALE_PARAMETERS,
        OID_GEN_RECEIVE_HASH,
#endif
#if PARANDIS_SUPPORT_RSC
        OID_TCP_RSC_STATISTICS
#endif
};

static const NDIS_GUID supportedGUIDs[]
{
    { NetKvm_LoggingGuid,    OID_VENDOR_1, NetKvm_Logging_SIZE, fNDIS_GUID_TO_OID | fNDIS_GUID_ALLOW_READ | fNDIS_GUID_ALLOW_WRITE },
    { NetKvm_StatisticsGuid, OID_VENDOR_2, NetKvm_Statistics_SIZE, fNDIS_GUID_TO_OID | fNDIS_GUID_ALLOW_READ | fNDIS_GUID_ALLOW_WRITE }
};

/**********************************************************
        For statistics header
***********************************************************/
static const ULONG SupportedStatisticsFlags =
    NDIS_STATISTICS_FLAGS_VALID_DIRECTED_FRAMES_RCV |
    NDIS_STATISTICS_FLAGS_VALID_DIRECTED_FRAMES_XMIT |
    NDIS_STATISTICS_FLAGS_VALID_DIRECTED_BYTES_RCV |
    NDIS_STATISTICS_FLAGS_VALID_DIRECTED_BYTES_XMIT |
    NDIS_STATISTICS_FLAGS_VALID_BYTES_RCV |
    NDIS_STATISTICS_FLAGS_VALID_BYTES_XMIT |
    NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_RCV |
    NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_RCV |
    NDIS_STATISTICS_FLAGS_VALID_MULTICAST_FRAMES_RCV |
    NDIS_STATISTICS_FLAGS_VALID_BROADCAST_FRAMES_RCV |
    NDIS_STATISTICS_FLAGS_VALID_MULTICAST_FRAMES_XMIT |
    NDIS_STATISTICS_FLAGS_VALID_BROADCAST_FRAMES_XMIT |
    NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_RCV |
    NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_RCV |
    NDIS_STATISTICS_FLAGS_VALID_RCV_ERROR |
    NDIS_STATISTICS_FLAGS_VALID_RCV_DISCARDS |
    NDIS_STATISTICS_FLAGS_VALID_XMIT_ERROR |
    NDIS_STATISTICS_FLAGS_VALID_XMIT_DISCARDS |
    NDIS_STATISTICS_FLAGS_VALID_MULTICAST_BYTES_XMIT |
    NDIS_STATISTICS_FLAGS_VALID_BROADCAST_BYTES_XMIT |
    0;

/**********************************************************
        For miniport registration
***********************************************************/
static const ULONG SupportedStatistics =
    NDIS_STATISTICS_XMIT_OK_SUPPORTED                   |
    NDIS_STATISTICS_RCV_OK_SUPPORTED                    |
    NDIS_STATISTICS_XMIT_ERROR_SUPPORTED                    |
    NDIS_STATISTICS_RCV_ERROR_SUPPORTED                     |
    NDIS_STATISTICS_RCV_NO_BUFFER_SUPPORTED                 |
    NDIS_STATISTICS_DIRECTED_BYTES_XMIT_SUPPORTED           |
    NDIS_STATISTICS_DIRECTED_FRAMES_XMIT_SUPPORTED          |
    NDIS_STATISTICS_MULTICAST_BYTES_XMIT_SUPPORTED          |
    NDIS_STATISTICS_MULTICAST_FRAMES_XMIT_SUPPORTED         |
    NDIS_STATISTICS_BROADCAST_BYTES_XMIT_SUPPORTED          |
    NDIS_STATISTICS_BROADCAST_FRAMES_XMIT_SUPPORTED         |
    NDIS_STATISTICS_DIRECTED_BYTES_RCV_SUPPORTED            |
    NDIS_STATISTICS_DIRECTED_FRAMES_RCV_SUPPORTED           |
    NDIS_STATISTICS_MULTICAST_BYTES_RCV_SUPPORTED           |
    NDIS_STATISTICS_MULTICAST_FRAMES_RCV_SUPPORTED          |
    NDIS_STATISTICS_BROADCAST_BYTES_RCV_SUPPORTED           |
    NDIS_STATISTICS_BROADCAST_FRAMES_RCV_SUPPORTED          |
    //NDIS_STATISTICS_RCV_CRC_ERROR_SUPPORTED               |
    NDIS_STATISTICS_TRANSMIT_QUEUE_LENGTH_SUPPORTED         |
    //NDIS_STATISTICS_BYTES_RCV_SUPPORTED                     |
    //NDIS_STATISTICS_BYTES_XMIT_SUPPORTED                    |
    NDIS_STATISTICS_RCV_DISCARDS_SUPPORTED                  |
    NDIS_STATISTICS_GEN_STATISTICS_SUPPORTED                |
    NDIS_STATISTICS_XMIT_DISCARDS_SUPPORTED                 |
    0;

/**********************************************************
For common query provides array of supported OID
***********************************************************/
void ParaNdis_GetSupportedOid(PVOID *pOidsArray, PULONG pLength)
{
    *pOidsArray     = SupportedOids;
    *pLength        = sizeof(SupportedOids);
}

/**********************************************************
statistics support information for statistics structure
(it is different from bitmask provided at miniport registration)
***********************************************************/
ULONG ParaNdis6_GetSupportedStatisticsFlags()
{
    return SupportedStatisticsFlags;
}

/**********************************************************
OID support information for miniport registration
***********************************************************/
void ParaNdis6_GetSupportedOid(NDIS_MINIPORT_ADAPTER_GENERAL_ATTRIBUTES *pGenAttributes)
{
    pGenAttributes->SupportedOidList = SupportedOids;
    pGenAttributes->SupportedOidListLength = sizeof(SupportedOids);
    pGenAttributes->SupportedStatistics = SupportedStatistics;
}

// WMI properties (set operation)
static NDIS_STATUS OnSetVendorSpecific1(PARANDIS_ADAPTER *pContext, tOidDesc *pOid)
{
    NDIS_STATUS status = STATUS_SUCCESS;
    UNREFERENCED_PARAMETER(pContext);
    status = ParaNdis_OidSetCopy(pOid, &virtioDebugLevel, sizeof(virtioDebugLevel));
    DPrintf(0, "DebugLevel => %d\n", virtioDebugLevel);
    return status;
}

static NDIS_STATUS OnSetVendorSpecific2(PARANDIS_ADAPTER *pContext, tOidDesc *pOid)
{
    ULONG dummy = 0;
    NDIS_STATUS status;
    UNREFERENCED_PARAMETER(pContext);
    status = ParaNdis_OidSetCopy(pOid, &dummy, sizeof(dummy));
    RtlZeroMemory(&pContext->extraStatistics, sizeof(pContext->extraStatistics));
    return status;
}

/*****************************************************************
Handles NDIS6 specific OID, all the rest handled by common handler
*****************************************************************/
static NDIS_STATUS ParaNdis_OidQuery(PARANDIS_ADAPTER *pContext, tOidDesc *pOid)
{
    union _tagtemp
    {
        NDIS_LINK_SPEED                         LinkSpeed;
        NDIS_INTERRUPT_MODERATION_PARAMETERS    InterruptModeration;
        NDIS_LINK_PARAMETERS                    LinkParameters;
#if PARANDIS_SUPPORT_RSS
        RSS_HASH_KEY_PARAMETERS                 RSSHashKeyParameters;
#endif
#if PARANDIS_SUPPORT_RSC
        NDIS_RSC_STATISTICS_INFO                RSCStatistics;
#endif
    } u;
    NDIS_STATUS  status = NDIS_STATUS_SUCCESS;
    PVOID pInfo  = NULL;
    ULONG ulSize = 0;
    BOOLEAN bFreeInfo = FALSE;
    NetKvm_Statistics wmiStatistics;

#define SETINFO(field, value) pInfo = &u.##field; ulSize = sizeof(u.##field); u.##field = (value)
    switch(pOid->Oid)
    {
        case OID_GEN_STATISTICS:
            pInfo  = &pContext->Statistics;
            ulSize = sizeof(pContext->Statistics);
            break;
        case OID_GEN_SUPPORTED_GUIDS:
#if NDIS_SUPPORT_NDIS61
            pInfo = (PVOID)&supportedGUIDs;
            ulSize = sizeof(supportedGUIDs);
#endif
            break;
        case OID_VENDOR_1:
            pInfo = &virtioDebugLevel;
            ulSize = sizeof(virtioDebugLevel);
            break;
        case OID_VENDOR_2:
            pInfo = &wmiStatistics;
            ulSize = sizeof(wmiStatistics);
            wmiStatistics.txChecksumOffload = pContext->extraStatistics.framesCSOffload;
            wmiStatistics.txLargeOffload = pContext->extraStatistics.framesLSO;
            wmiStatistics.rxPriority = pContext->extraStatistics.framesRxPriority;
            wmiStatistics.rxChecksumOK = pContext->extraStatistics.framesRxCSHwOK;
            wmiStatistics.rxCoalescedWin = pContext->extraStatistics.framesCoalescedWindows;
            wmiStatistics.rxCoalescedHost = pContext->extraStatistics.framesCoalescedHost;
            break;

        case OID_GEN_INTERRUPT_MODERATION:
            u.InterruptModeration.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
            u.InterruptModeration.Header.Size = sizeof(u.InterruptModeration);
            u.InterruptModeration.Header.Revision = NDIS_INTERRUPT_MODERATION_PARAMETERS_REVISION_1;
            u.InterruptModeration.Flags = 0;
            u.InterruptModeration.InterruptModeration = NdisInterruptModerationNotSupported;
            pInfo = &u.InterruptModeration;
            ulSize = sizeof(u.InterruptModeration);
            break;
#if PARANDIS_SUPPORT_RSS
        case OID_GEN_RECEIVE_HASH:
            pInfo = &u.RSSHashKeyParameters;
            ulSize = ParaNdis6_QueryReceiveHash(&pContext->RSSParameters, &u.RSSHashKeyParameters);
            break;
#endif
#if PARANDIS_SUPPORT_RSC
        case OID_TCP_RSC_STATISTICS:
            u.RSCStatistics.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
            u.RSCStatistics.Header.Revision = NDIS_RSC_STATISTICS_REVISION_1;
            u.RSCStatistics.Header.Size = NDIS_SIZEOF_RSC_STATISTICS_REVISION_1;
            u.RSCStatistics.CoalescedOctets = pContext->RSC.Statistics.CoalescedOctets.QuadPart;
            u.RSCStatistics.CoalescedPkts = pContext->RSC.Statistics.CoalescedPkts.QuadPart;
            u.RSCStatistics.CoalesceEvents = pContext->RSC.Statistics.CoalesceEvents.QuadPart;
            u.RSCStatistics.Aborts = 0;

            pInfo = &u.RSCStatistics;
            ulSize = sizeof(u.RSCStatistics);
            break;
#endif
        default:
            return ParaNdis_OidQueryCommon(pContext, pOid);
    }
    if (status == NDIS_STATUS_SUCCESS)
    {
        status = ParaNdis_OidQueryCopy(pOid, pInfo, ulSize, bFreeInfo);
    }
    return status;
}

/**********************************************************
NDIS required procedure for OID support
Parameters:
    context
    PNDIS_OID_REQUEST  pNdisRequest         NDIS oid request
Return value:
    NDIS status, as returned from supporting procedure
    NDIS_STATUS_NOT_SUPPORTED if support for get/set is not defined in the table
***********************************************************/
NDIS_STATUS ParaNdis6_OidRequest(
    NDIS_HANDLE miniportAdapterContext,
    PNDIS_OID_REQUEST  pNdisRequest)
{
    NDIS_STATUS  status = NDIS_STATUS_NOT_SUPPORTED;
    tOidWhatToDo Rules;
    PARANDIS_ADAPTER *pContext = (PARANDIS_ADAPTER *)miniportAdapterContext;
    tOidDesc _oid;
    _oid.Reserved = pNdisRequest;
    ParaNdis_GetOidSupportRules(pNdisRequest->DATA.SET_INFORMATION.Oid, &Rules, OidsDB);
    _oid.ulToDoFlags = Rules.Flags;

    ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, pNdisRequest->DATA.SET_INFORMATION.Oid, pNdisRequest->RequestType, 1);
    DPrintf(Rules.nEntryLevel, "[%s] OID type %d, id 0x%X(%s) of %d\n", __FUNCTION__,
                pNdisRequest->RequestType,
                pNdisRequest->DATA.SET_INFORMATION.Oid,
                Rules.name,
                pNdisRequest->DATA.SET_INFORMATION.InformationBufferLength);

    if (pContext->bSurprizeRemoved) status = NDIS_STATUS_NOT_ACCEPTED;
    else switch(pNdisRequest->RequestType)
    {
        case NdisRequestQueryStatistics:
            if (Rules.Flags & ohfQueryStatOnly)
            {
                // fall to query;
            }
            else
            {
                status = NDIS_STATUS_NOT_SUPPORTED;
                break;
            }
            __fallthrough;
        case NdisRequestQueryInformation:
            if (Rules.Flags & ohfQuery)
            {
                _oid.InformationBuffer = pNdisRequest->DATA.QUERY_INFORMATION.InformationBuffer;
                _oid.InformationBufferLength = pNdisRequest->DATA.QUERY_INFORMATION.InformationBufferLength;
                _oid.Oid = pNdisRequest->DATA.QUERY_INFORMATION.Oid;
                _oid.pBytesWritten = &pNdisRequest->DATA.QUERY_INFORMATION.BytesWritten;
                _oid.pBytesNeeded = &pNdisRequest->DATA.QUERY_INFORMATION.BytesNeeded;
                _oid.pBytesRead = &pNdisRequest->DATA.QUERY_INFORMATION.BytesWritten;
                status = ParaNdis_OidQuery(pContext, &_oid);
            }
            break;
        case NdisRequestSetInformation:
            if (Rules.Flags & ohfSet)
            {
                if (Rules.OidSetProc)
                {
                    _oid.InformationBuffer = pNdisRequest->DATA.SET_INFORMATION.InformationBuffer;
                    _oid.InformationBufferLength = pNdisRequest->DATA.SET_INFORMATION.InformationBufferLength;
                    _oid.Oid = pNdisRequest->DATA.SET_INFORMATION.Oid;
                    _oid.pBytesWritten = &pNdisRequest->DATA.SET_INFORMATION.BytesRead;
                    _oid.pBytesNeeded = &pNdisRequest->DATA.SET_INFORMATION.BytesNeeded;
                    _oid.pBytesRead = &pNdisRequest->DATA.SET_INFORMATION.BytesRead;
                    status = Rules.OidSetProc(pContext, &_oid);
                }
                else
                {
                    DPrintf(0, "Error: Inconsistent OIDDB, oid %s\n", Rules.name);
                }
            }
            break;
        default:
            DPrintf(Rules.nExitFailLevel, "Error: Unsupported OID type %d, id 0x%X(%s)\n",
                pNdisRequest->RequestType, Rules.oid, Rules.name);
            status = NDIS_STATUS_NOT_SUPPORTED;
            break;
    }
    ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, pNdisRequest->DATA.SET_INFORMATION.Oid, status, 0);
    if (status != NDIS_STATUS_PENDING)
    {
        DPrintf(((status != NDIS_STATUS_SUCCESS) ? Rules.nExitFailLevel : Rules.nExitOKLevel),
            "[%s] OID type %d, id 0x%X(%s) (%X)\n", __FUNCTION__,
            pNdisRequest->RequestType, Rules.oid, Rules.name, status);
    }
    return status;
}

/**********************************************************
NDIS required procedure for OID cancel
May be used only for OID returning PENDING
Parameters:
    irrelevant
***********************************************************/
VOID ParaNdis6_OidCancelRequest(
        NDIS_HANDLE hMiniportAdapterContext,
        PVOID pRequestId)
{
    UNREFERENCED_PARAMETER(hMiniportAdapterContext);
    UNREFERENCED_PARAMETER(pRequestId);
}

static void OnSetPowerWorkItem(PVOID  WorkItemContext, NDIS_HANDLE  NdisIoWorkItemHandle)
{
    if (WorkItemContext)
    {
        tPowerWorkItem *pwi = (tPowerWorkItem *)WorkItemContext;
        PARANDIS_ADAPTER *pContext = pwi->pContext;
        PNDIS_OID_REQUEST pRequest = (PNDIS_OID_REQUEST)pwi->request;
        NDIS_STATUS status = NDIS_STATUS_SUCCESS;
    #ifdef DEBUG_TIMING
        LARGE_INTEGER TickCount;
        LARGE_INTEGER SysTime;

        KeQueryTickCount(&TickCount);
        NdisGetCurrentSystemTime(&SysTime);
        DPrintf(0, "\n%s>> CPU #%d, perf-counter %I64d, tick count %I64d, NDIS_sys_time %I64d\n", __FUNCTION__, KeGetCurrentProcessorNumber(), KeQueryPerformanceCounter(NULL).QuadPart,TickCount.QuadPart, SysTime.QuadPart);
    #endif

        if (pwi->state == NetDeviceStateD0)
        {
            status = ParaNdis_PowerOn(pContext);
        }
        else
        {
            ParaNdis_PowerOff(pContext);
        }
        NdisFreeMemory(pwi, 0, 0);
        NdisFreeIoWorkItem(NdisIoWorkItemHandle);
        ParaNdis_DebugHistory(pContext, hopOidRequest, NULL, pRequest->DATA.SET_INFORMATION.Oid, status, 2);
        NdisMOidRequestComplete(pContext->MiniportHandle, pRequest, status);
    }
}

/**********************************************************
NDIS6.X handler of power management
***********************************************************/
NDIS_STATUS ParaNdis_OnSetPower(PARANDIS_ADAPTER *pContext, tOidDesc *pOid)
{
    NDIS_STATUS status;
    NDIS_DEVICE_POWER_STATE newState;
#ifdef DEBUG_TIMING
    LARGE_INTEGER TickCount;
    LARGE_INTEGER SysTime;

    KeQueryTickCount(&TickCount);
    NdisGetCurrentSystemTime(&SysTime);
    DPrintf(0, "\n%s>> CPU #%d, perf-counter %I64d, tick count %I64d, NDIS_sys_time %I64d\n", __FUNCTION__, KeGetCurrentProcessorNumber(), KeQueryPerformanceCounter(NULL).QuadPart,TickCount.QuadPart, SysTime.QuadPart);
#endif

    DEBUG_ENTRY(0);

    status = ParaNdis_OidSetCopy(pOid, &newState, sizeof(newState));
    if (status == NDIS_STATUS_SUCCESS)
    {
        NDIS_HANDLE hwo = NdisAllocateIoWorkItem(pContext->MiniportHandle);
        tPowerWorkItem *pwi = (tPowerWorkItem *) ParaNdis_AllocateMemory(pContext, sizeof(tPowerWorkItem));
        status = NDIS_STATUS_FAILURE;
        if (pwi && hwo)
        {
            pwi->pContext = pContext;
            pwi->state    = newState;
            pwi->WorkItem = hwo;
            pwi->request = (PNDIS_OID_REQUEST)pOid->Reserved;
            NdisQueueIoWorkItem(hwo, OnSetPowerWorkItem, pwi);
            status = NDIS_STATUS_PENDING;
        }
        else
        {
            if (pwi) NdisFreeMemory(pwi, 0, 0);
            if (hwo) NdisFreeIoWorkItem(hwo);
        }
    }
    return status;
}

static void DumpOffloadStructure(NDIS_OFFLOAD *po, LPCSTR message)
{
    int level = 1;
    ULONG *pul;
    DPrintf(level, "[%s](%s)\n", __FUNCTION__, message);
    pul = (ULONG *)&po->Checksum.IPv4Transmit;
    DPrintf(level, "CSV4TX:(%d,%d)\n", pul[0], pul[1]);
    pul = (ULONG *)&po->Checksum.IPv4Receive;
    DPrintf(level, "CSV4RX:(%d,%d)\n", pul[0], pul[1]);
    pul = (ULONG *)&po->Checksum.IPv6Transmit;
    DPrintf(level, "CSV6TX:(%d,%d,%d,%d,%d)\n", pul[0], pul[1], pul[2], pul[3], pul[4]);
    pul = (ULONG *)&po->Checksum.IPv6Receive;
    DPrintf(level, "CSV6RX:(%d,%d,%d,%d,%d)\n", pul[0], pul[1], pul[2], pul[3], pul[4]);
    pul = (ULONG *)&po->LsoV1;
    DPrintf(level, "LSOV1 :(%d,%d,%d,%d)\n", pul[0], pul[1], pul[2], pul[3]);
    pul = (ULONG *)&po->LsoV2.IPv4;
    DPrintf(level, "LSO4V2:(%d,%d,%d)\n", pul[0], pul[1], pul[2]);
    pul = (ULONG *)&po->LsoV2.IPv6;
    DPrintf(level, "LSO6V2:(%d,%d,%d,%d)\n", pul[0], pul[1], pul[2], pul[3]);
#ifdef PARANDIS_SUPPORT_RSC
    DPrintf(level, "RSC:(IPv4: Enabled=%ul, IPv6: Enabled=%ul)\n", po->Rsc.IPv4.Enabled, po->Rsc.IPv6.Enabled);
#endif
}

#define OFFLOAD_FEATURE_SUPPORT(flag) (flag) ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED

static void FillOffloadStructure(NDIS_OFFLOAD *po, tOffloadSettingsFlags f)
{
    NDIS_TCP_IP_CHECKSUM_OFFLOAD *pcso = &po->Checksum;
    NDIS_TCP_LARGE_SEND_OFFLOAD_V1 *plso = &po->LsoV1;
    NDIS_TCP_LARGE_SEND_OFFLOAD_V2 *plso2 = &po->LsoV2;
    NdisZeroMemory(po, sizeof(*po));
    po->Header.Type = NDIS_OBJECT_TYPE_OFFLOAD;
#if (NDIS_SUPPORT_NDIS630)
    po->Header.Revision = NDIS_OFFLOAD_REVISION_3;
    po->Header.Size = NDIS_SIZEOF_NDIS_OFFLOAD_REVISION_3;
#else
    po->Header.Revision = NDIS_OFFLOAD_REVISION_1;
    po->Header.Size = NDIS_SIZEOF_NDIS_OFFLOAD_REVISION_1;
#endif
    pcso->IPv4Transmit.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3;
    pcso->IPv4Transmit.IpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxIPChecksum);
    pcso->IPv4Transmit.IpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxIPOptions);
    pcso->IPv4Transmit.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPChecksum);
    pcso->IPv4Transmit.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPOptions);
    pcso->IPv4Transmit.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxUDPChecksum);

    pcso->IPv6Transmit.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3;
    pcso->IPv6Transmit.IpExtensionHeadersSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxIPv6Ext);
    pcso->IPv6Transmit.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPv6Checksum);
    pcso->IPv6Transmit.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fTxTCPv6Options);
    pcso->IPv6Transmit.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fTxUDPv6Checksum);

    pcso->IPv4Receive.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3;
    pcso->IPv4Receive.IpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxIPChecksum);
    pcso->IPv4Receive.IpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxIPOptions);
    pcso->IPv4Receive.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPChecksum);
    pcso->IPv4Receive.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPOptions);
    pcso->IPv4Receive.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxUDPChecksum);

    pcso->IPv6Receive.Encapsulation = NDIS_ENCAPSULATION_IEEE_802_3;
    pcso->IPv6Receive.IpExtensionHeadersSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxIPv6Ext);
    pcso->IPv6Receive.TcpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPv6Checksum);
    pcso->IPv6Receive.TcpOptionsSupported = OFFLOAD_FEATURE_SUPPORT(f.fRxTCPv6Options);
    pcso->IPv6Receive.UdpChecksum = OFFLOAD_FEATURE_SUPPORT(f.fRxUDPv6Checksum);

    plso->IPv4.Encapsulation = f.fTxLso ? NDIS_ENCAPSULATION_IEEE_802_3 : NDIS_ENCAPSULATION_NOT_SUPPORTED;
    plso->IPv4.TcpOptions = (f.fTxLsoTCP && f.fTxLso) ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED;
    plso->IPv4.IpOptions  = (f.fTxLsoIP  && f.fTxLso) ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED;
    plso->IPv4.MaxOffLoadSize = f.fTxLso ? PARANDIS_MAX_LSO_SIZE : 0;
    plso->IPv4.MinSegmentCount = f.fTxLso ? PARANDIS_MIN_LSO_SEGMENTS : 0;
    plso2->IPv4.Encapsulation = plso->IPv4.Encapsulation;
    plso2->IPv4.MaxOffLoadSize = plso->IPv4.MaxOffLoadSize;
    plso2->IPv4.MinSegmentCount = plso->IPv4.MinSegmentCount;

    plso2->IPv6.Encapsulation = f.fTxLsov6 ? NDIS_ENCAPSULATION_IEEE_802_3 : NDIS_ENCAPSULATION_NOT_SUPPORTED;
    plso2->IPv6.IpExtensionHeadersSupported = f.fTxLsov6IP ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED;
    plso2->IPv6.MaxOffLoadSize = f.fTxLsov6 ? PARANDIS_MAX_LSO_SIZE : 0;
    plso2->IPv6.MinSegmentCount = f.fTxLsov6 ? PARANDIS_MIN_LSO_SEGMENTS : 0;
    plso2->IPv6.TcpOptionsSupported = f.fTxLsov6TCP ? NDIS_OFFLOAD_SUPPORTED : NDIS_OFFLOAD_NOT_SUPPORTED;
}

void ParaNdis6_FillOffloadConfiguration(PARANDIS_ADAPTER *pContext)
{
    NDIS_OFFLOAD *po = &pContext->ReportedOffloadConfiguration;
    FillOffloadStructure(po, pContext->Offload.flags);
#if PARANDIS_SUPPORT_RSC
    po->Rsc.IPv4.Enabled = pContext->RSC.bIPv4Enabled;
    po->Rsc.IPv6.Enabled = pContext->RSC.bIPv6Enabled;
#endif
}

void ParaNdis6_FillOffloadCapabilities(PARANDIS_ADAPTER *pContext)
{
    tOffloadSettingsFlags f;
    NDIS_OFFLOAD *po = &pContext->ReportedOffloadCapabilities;
    ParaNdis_ResetOffloadSettings(pContext, &f, NULL);
    FillOffloadStructure(po, f);
#if PARANDIS_SUPPORT_RSC
    po->Rsc.IPv4.Enabled = pContext->RSC.bIPv4SupportedHW;
    po->Rsc.IPv6.Enabled = pContext->RSC.bIPv6SupportedHW;
#endif
}

#if 0
static const NDIS_TCP_IP_CHECKSUM_OFFLOAD CheckSumAllOff =
{
    {
        //IPV4Tx
        NDIS_ENCAPSULATION_IEEE_802_3,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE
    },
    {
        //IPV4Rx
        NDIS_ENCAPSULATION_NOT_SUPPORTED,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE
    },
    {
        //IPV6Tx
        NDIS_ENCAPSULATION_NOT_SUPPORTED,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE
    },
    {
        //IPV6Rx
        NDIS_ENCAPSULATION_NOT_SUPPORTED,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE,
        NDIS_OFFLOAD_SET_NO_CHANGE
    }
};

static void BuildOffloadStatusReport(
    const NDIS_TCP_IP_CHECKSUM_OFFLOAD *Current,
    NDIS_TCP_IP_CHECKSUM_OFFLOAD *update)
{
    // see
#if 1
#define SYNC_STRUCT(_struct, field) update->##_struct.##field = (Current->##_struct.##field == NDIS_OFFLOAD_SUPPORTED) ? NDIS_OFFLOAD_SET_ON : NDIS_OFFLOAD_SET_OFF
#define SYNC_FIELD_TX4(field) SYNC_STRUCT(IPv4Transmit,field)
#define SYNC_FIELD_RX4(field) SYNC_STRUCT(IPv4Receive,field)
#define SYNC_FIELD_TX6(field) SYNC_STRUCT(IPv6Transmit,field)
#define SYNC_FIELD_RX6(field) SYNC_STRUCT(IPv6Receive,field)

    SYNC_FIELD_TX4(IpChecksum);
    SYNC_FIELD_TX4(IpOptionsSupported);
    SYNC_FIELD_TX4(TcpChecksum);
    SYNC_FIELD_TX4(TcpOptionsSupported);
    SYNC_FIELD_TX4(UdpChecksum);
    SYNC_FIELD_RX4(IpChecksum);
    SYNC_FIELD_RX4(IpOptionsSupported);
    SYNC_FIELD_RX4(TcpChecksum);
    SYNC_FIELD_RX4(TcpOptionsSupported);
    SYNC_FIELD_RX4(UdpChecksum);
    SYNC_FIELD_TX6(IpExtensionHeadersSupported);
    SYNC_FIELD_TX6(TcpOptionsSupported);
    SYNC_FIELD_TX6(TcpChecksum);
    SYNC_FIELD_TX6(UdpChecksum);
    SYNC_FIELD_RX6(IpExtensionHeadersSupported);
    SYNC_FIELD_RX6(TcpOptionsSupported);
    SYNC_FIELD_RX6(TcpChecksum);
    SYNC_FIELD_RX6(UdpChecksum);
#else
    RtlCopyMemory(&diff->Checksum, &CheckSumAllOff, sizeof(diff->Checksum));
#endif
}
#endif //0

static const char *MakeTxRxString(ULONG bTx, ULONG bRx)
{
    const char *const titles[] = {"None", "Tx", "Rx", "TxRx"};
    ULONG index = !!bTx + 2 * !!bRx;
    return titles[index];
}

static const char *MakeOffloadParameterString(UCHAR val)
{
    switch(val)
    {
        case NDIS_OFFLOAD_PARAMETERS_NO_CHANGE:
            return "NoChange";
        case NDIS_OFFLOAD_PARAMETERS_TX_RX_DISABLED:
            return "None";
        case NDIS_OFFLOAD_PARAMETERS_TX_ENABLED_RX_DISABLED:
            return "Tx";
        case NDIS_OFFLOAD_PARAMETERS_RX_ENABLED_TX_DISABLED:
            return "Rx";
        case NDIS_OFFLOAD_PARAMETERS_TX_RX_ENABLED:
            return "TxRx";
        default:
            break;
    }
    return "OUT OF RANGE";
}

static void SendOffloadStatusIndication(PARANDIS_ADAPTER *pContext)
{
    NDIS_STATUS_INDICATION  indication;
    PNDIS_OID_REQUEST pRequest = NULL;
    NDIS_OFFLOAD offload = pContext->ReportedOffloadConfiguration;
    NdisZeroMemory(&indication, sizeof(indication));
    indication.Header.Type = NDIS_OBJECT_TYPE_STATUS_INDICATION;
    indication.Header.Revision = NDIS_STATUS_INDICATION_REVISION_1;
    indication.Header.Size = NDIS_SIZEOF_STATUS_INDICATION_REVISION_1;
    indication.SourceHandle = pContext->MiniportHandle;
    indication.StatusCode = NDIS_STATUS_TASK_OFFLOAD_CURRENT_CONFIG;
    indication.StatusBuffer = &offload;
    indication.StatusBufferSize = sizeof(offload);
    // we shall not do that for offload indications,
    // it is only for case we return NDIS_STATUS_INDICATION_REQUIRED from OID Handler
    // if (pOid) pRequest = (PNDIS_OID_REQUEST)pOid->Reserved;
    if (pRequest)
    {
        indication.RequestId = pRequest->RequestId;
        indication.DestinationHandle = pRequest->RequestHandle;
    }
    DPrintf(0, "Indicating offload change");
    NdisMIndicateStatusEx(pContext->MiniportHandle , &indication);
}

static ULONG SetOffloadField(
    const char *name,
    BOOLEAN isTx,
    ULONG current,
    ULONG isSupportedTx,
    ULONG isSupportedRx,
    UCHAR TxRxValue,
    BOOLEAN *pbFailed)
{
    if (!*pbFailed)
    {
        DPrintf(0, "[%s] IN %s %s: current=%d Supported %s Requested %s\n",
                __FUNCTION__, name, isTx? "TX" : "RX", current,
                MakeTxRxString(isSupportedTx, isSupportedRx),
                MakeOffloadParameterString(TxRxValue));

        switch(TxRxValue)
        {
        case NDIS_OFFLOAD_PARAMETERS_TX_RX_DISABLED:
            current = 0;
            break;
        case NDIS_OFFLOAD_PARAMETERS_TX_RX_ENABLED:
            if (!isSupportedTx || !isSupportedRx)
            {
                *pbFailed = TRUE;
                current   = isTx ? isSupportedTx : isSupportedRx;
            }
            else
            {
                current = 1;
            }
            break;
        case NDIS_OFFLOAD_PARAMETERS_TX_ENABLED_RX_DISABLED:
            if (isTx)
            {
                if (!isSupportedTx) *pbFailed = TRUE;
                current = isSupportedTx;
            }
            else
            {
                current = 0;
            }
            break;
        case NDIS_OFFLOAD_PARAMETERS_RX_ENABLED_TX_DISABLED:
            if (!isTx)
            {
                if (!isSupportedRx) *pbFailed = TRUE;
                current = isSupportedRx;
            }
            else
            {
                current = 0;
            }
            break;
        case NDIS_OFFLOAD_PARAMETERS_NO_CHANGE:
            __fallthrough;
        default:
            break;
        }

        DPrintf(0, "[%s] OUT %s %s: new=%d (%saccepted)\n", __FUNCTION__, name, isTx? "TX" : "RX", current, *pbFailed ? "NOT " : "");
    }
    return current;
}

static NDIS_STATUS ApplyOffloadConfiguration(PARANDIS_ADAPTER *pContext,
    NDIS_OFFLOAD_PARAMETERS *pop, tOidDesc *pOid)
{
    BOOLEAN bFailed = FALSE;
    tOffloadSettingsFlags fSupported;
    tOffloadSettingsFlags fPresent = pContext->Offload.flags;
    tOffloadSettingsFlags *pf = &fPresent;

    DPrintf(0, "[%s] Requested: V4:IPCS=%s,TCPCS=%s,UDPCS=%s V6:TCPCS=%s,UDPCS=%s\n",
                __FUNCTION__,
                MakeOffloadParameterString(pop->IPv4Checksum),
                MakeOffloadParameterString(pop->TCPIPv4Checksum),
                MakeOffloadParameterString(pop->UDPIPv4Checksum),
                MakeOffloadParameterString(pop->TCPIPv6Checksum),
                MakeOffloadParameterString(pop->UDPIPv6Checksum));

    ParaNdis_ResetOffloadSettings(pContext, &fSupported, NULL);
    pf->fTxIPChecksum = SetOffloadField("TxIPChecksum", TRUE,
        pf->fTxIPChecksum, fSupported.fTxIPChecksum,
        fSupported.fRxIPChecksum, pop->IPv4Checksum, &bFailed);
    pf->fTxIPOptions = pf->fTxIPChecksum && fSupported.fTxIPOptions;
    pf->fTxTCPChecksum = SetOffloadField("TxTCPChecksum", TRUE,
        pf->fTxTCPChecksum, fSupported.fTxTCPChecksum,
        fSupported.fRxTCPChecksum, pop->TCPIPv4Checksum, &bFailed);
    pf->fTxTCPOptions = pf->fTxTCPChecksum && fSupported.fTxTCPOptions;
    pf->fTxUDPChecksum = SetOffloadField("TxUDPChecksum", TRUE,
        pf->fTxUDPChecksum, fSupported.fTxUDPChecksum,
        fSupported.fRxUDPChecksum, pop->UDPIPv4Checksum, &bFailed);
    pf->fRxIPChecksum = SetOffloadField("RxIPChecksum", FALSE,
        pf->fRxIPChecksum, fSupported.fTxIPChecksum,
        fSupported.fRxIPChecksum, pop->IPv4Checksum, &bFailed);
    pf->fRxIPOptions = pf->fRxIPChecksum && fSupported.fRxIPOptions;
    pf->fRxTCPChecksum = SetOffloadField("RxTCPChecksum", FALSE,
        pf->fRxTCPChecksum, fSupported.fTxTCPChecksum,
        fSupported.fRxTCPChecksum, pop->TCPIPv4Checksum, &bFailed);
    pf->fRxTCPOptions = pf->fRxTCPChecksum && fSupported.fRxTCPOptions;
    pf->fRxUDPChecksum = SetOffloadField("RxUDPChecksum", FALSE,
        pf->fRxUDPChecksum, fSupported.fTxUDPChecksum,
        fSupported.fRxUDPChecksum, pop->UDPIPv4Checksum, &bFailed);
    pf->fTxTCPv6Checksum = SetOffloadField("TxTCPv6Checksum", TRUE,
        pf->fTxTCPv6Checksum, fSupported.fTxTCPv6Checksum,
        fSupported.fRxTCPv6Checksum, pop->TCPIPv6Checksum, &bFailed);
    pf->fTxTCPv6Options = pf->fTxTCPv6Checksum && fSupported.fTxTCPv6Options;
    pf->fTxIPv6Ext = pf->fTxTCPv6Checksum && fSupported.fTxIPv6Ext;
    pf->fTxUDPv6Checksum = SetOffloadField("TxUDPv6Checksum", TRUE,
        pf->fTxUDPv6Checksum, fSupported.fTxUDPv6Checksum,
        fSupported.fRxUDPv6Checksum, pop->UDPIPv6Checksum, &bFailed);
    pf->fRxTCPv6Checksum = SetOffloadField("RxTCPv6Checksum", FALSE,
        pf->fRxTCPv6Checksum, fSupported.fTxTCPv6Checksum,
        fSupported.fRxTCPv6Checksum, pop->TCPIPv6Checksum, &bFailed);
    pf->fRxIPv6Ext = pf->fRxTCPv6Checksum && fSupported.fRxIPv6Ext;
    pf->fRxTCPv6Options = pf->fRxTCPv6Checksum && fSupported.fRxTCPv6Options;
    pf->fRxUDPv6Checksum = SetOffloadField("RxUDPv6Checksum", FALSE,
        pf->fRxUDPv6Checksum, fSupported.fTxUDPv6Checksum,
        fSupported.fRxUDPv6Checksum, pop->UDPIPv6Checksum, &bFailed);

    DPrintf(0, "[%s] Result: TCPv4:%s,UDPv4:%s,IPCS:%s TCPv6:%s,UDPv6:%s\n", __FUNCTION__,
        MakeTxRxString(pf->fTxTCPChecksum, pf->fRxTCPChecksum),
        MakeTxRxString(pf->fTxUDPChecksum, pf->fRxUDPChecksum),
        MakeTxRxString(pf->fTxIPChecksum, pf->fRxIPChecksum),
        MakeTxRxString(pf->fTxTCPv6Checksum, pf->fRxTCPv6Checksum),
        MakeTxRxString(pf->fTxUDPv6Checksum, pf->fRxUDPv6Checksum)
        );

    if (NDIS_OFFLOAD_PARAMETERS_LSOV1_DISABLED == pop->LsoV1 || NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED == pop->LsoV2IPv4)
    {
        pf->fTxLso = 0;
    }
    else if (NDIS_OFFLOAD_PARAMETERS_LSOV1_ENABLED == pop->LsoV1 || NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED  == pop->LsoV2IPv4)
    {
        if (fSupported.fTxLso) pf->fTxLso = 1;
        else
            bFailed = TRUE;
    }

    if (NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED == pop->LsoV2IPv6)
    {
        pf->fTxLsov6 = 0;
    }
    else if (NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED  == pop->LsoV2IPv6)
    {
        if (fSupported.fTxLsov6) pf->fTxLsov6 = 1;
        else
            bFailed = TRUE;
    }

    pf->fTxLsoIP = pf->fTxLso && fSupported.fTxLsoIP;
    pf->fTxLsoTCP = pf->fTxLso && fSupported.fTxLsoTCP;

    if ((NDIS_OFFLOAD_PARAMETERS_LSOV1_DISABLED == pop->LsoV1 && NDIS_OFFLOAD_PARAMETERS_LSOV2_ENABLED  == pop->LsoV2IPv4) ||
        (NDIS_OFFLOAD_PARAMETERS_LSOV1_ENABLED == pop->LsoV1 && NDIS_OFFLOAD_PARAMETERS_LSOV2_DISABLED  == pop->LsoV2IPv4))
    {
        bFailed = TRUE;
    }

    DPrintf(0, "[%s] Result: LSO: v4 %d, v6 %d\n", __FUNCTION__, pf->fTxLso, pf->fTxLsov6);
    DPrintf(0, "[%s] Final: the request %saccepted\n", __FUNCTION__, bFailed ? "NOT " : "");

    if (bFailed && pOid)
        return NDIS_STATUS_INVALID_PARAMETER;

    // at initialization time due to absence of pOid
    // we initialize the ReportedOffloadConfiguration
    // according to our capabilities
    pContext->Offload.flags = fPresent;
    ParaNdis6_FillOffloadConfiguration(pContext);

    return NDIS_STATUS_SUCCESS;
}

static
NDIS_STATUS OnSetRSCParameters(PPARANDIS_ADAPTER pContext, PNDIS_OFFLOAD_PARAMETERS op)
{
#if PARANDIS_SUPPORT_RSC
    UINT64 GuestOffloads;

    if(op->Header.Revision != NDIS_OFFLOAD_PARAMETERS_REVISION_3)
        return NDIS_STATUS_SUCCESS;

    if((op->RscIPv4 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE) &&
        (!pContext->RSC.bIPv4SupportedSW ||
         !pContext->RSC.bIPv4SupportedHW ||
         !pContext->RSC.bHasDynamicConfig))
        return NDIS_STATUS_NOT_SUPPORTED;

    if((op->RscIPv6 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE) &&
        (!pContext->RSC.bIPv6SupportedSW ||
         !pContext->RSC.bIPv6SupportedHW ||
         !pContext->RSC.bHasDynamicConfig))
        return NDIS_STATUS_NOT_SUPPORTED;

    if(op->RscIPv4 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE)
        pContext->RSC.bIPv4Enabled = (op->RscIPv4 == NDIS_OFFLOAD_PARAMETERS_RSC_ENABLED);

    if(op->RscIPv6 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE)
        pContext->RSC.bIPv6Enabled = (op->RscIPv6 == NDIS_OFFLOAD_PARAMETERS_RSC_ENABLED);

    if (op->RscIPv4 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE && pContext->RSC.bIPv4SupportedQEMU)
    {
        pContext->RSC.bIPv4EnabledQEMU = (op->RscIPv4 == NDIS_OFFLOAD_PARAMETERS_RSC_ENABLED);
    }

    if (op->RscIPv6 != NDIS_OFFLOAD_PARAMETERS_NO_CHANGE && pContext->RSC.bIPv6SupportedQEMU)
    {
        pContext->RSC.bIPv6EnabledQEMU = (op->RscIPv6 == NDIS_OFFLOAD_PARAMETERS_RSC_ENABLED);
    }

    GuestOffloads = 1 << VIRTIO_NET_F_GUEST_CSUM                                        |
                    ((pContext->RSC.bIPv4Enabled) ? (1 << VIRTIO_NET_F_GUEST_TSO4) : 0) |
                    ((pContext->RSC.bIPv6Enabled) ? (1 << VIRTIO_NET_F_GUEST_TSO6) : 0) |
                    ((pContext->RSC.bIPv4EnabledQEMU) ? ((UINT64)1 << VIRTIO_NET_F_GUEST_RSC4) : 0) |
                    ((pContext->RSC.bIPv6EnabledQEMU) ? ((UINT64)1 << VIRTIO_NET_F_GUEST_RSC6) : 0);

    ParaNdis_UpdateGuestOffloads(pContext, GuestOffloads);
#else
    UNREFERENCED_PARAMETER(pContext);
    UNREFERENCED_PARAMETER(op);
#endif /* PARANDIS_SUPPORT_RSC */

    return STATUS_SUCCESS;
}

NDIS_STATUS OnSetOffloadParameters(PARANDIS_ADAPTER *pContext, tOidDesc *pOid)
{
    NDIS_STATUS status;
    NDIS_OFFLOAD_PARAMETERS op = {0};

    if(pOid->InformationBufferLength < NDIS_SIZEOF_OFFLOAD_PARAMETERS_REVISION_1)
        return NDIS_STATUS_BUFFER_TOO_SHORT;

    status = ParaNdis_OidSetCopy(pOid, &op, sizeof(op));

    if(status != NDIS_STATUS_SUCCESS)
        return status;

    status = OnSetRSCParameters(pContext, &op);

    if(status != NDIS_STATUS_SUCCESS)
        return status;

    status = ApplyOffloadConfiguration(pContext, &op, pOid);

    if(status != NDIS_STATUS_SUCCESS)
        return status;

    DumpOffloadStructure(&pContext->ReportedOffloadConfiguration, "Updated");
    SendOffloadStatusIndication(pContext);

    return NDIS_STATUS_SUCCESS;
}

void ParaNdis6_ApplyOffloadPersistentConfiguration(PARANDIS_ADAPTER *pContext)
{
    // see NDIS_OFFLOAD_PARAMETERS_TX_RX_DISABLED and below
    // this unobvious code translates setting from registry conventions
    // (where 0 = disable) to NDIS offload parameters (where 1 = disable)
    pContext->InitialOffloadParameters.LsoV1++;
    pContext->InitialOffloadParameters.LsoV2IPv4++;
    pContext->InitialOffloadParameters.LsoV2IPv6++;
    pContext->InitialOffloadParameters.IPv4Checksum++;
    pContext->InitialOffloadParameters.TCPIPv4Checksum++;
    pContext->InitialOffloadParameters.TCPIPv6Checksum++;
    pContext->InitialOffloadParameters.UDPIPv4Checksum++;
    pContext->InitialOffloadParameters.UDPIPv6Checksum++;

    ApplyOffloadConfiguration(pContext,&pContext->InitialOffloadParameters, NULL);
    ParaNdis6_FillOffloadCapabilities(pContext);
}

NDIS_STATUS OnSetOffloadEncapsulation(PARANDIS_ADAPTER *pContext, tOidDesc *pOid)
{
    NDIS_OFFLOAD_ENCAPSULATION encaps;
    NDIS_STATUS status;
    status = ParaNdis_OidSetCopy(pOid, &encaps, sizeof(encaps));
    if (status == NDIS_STATUS_SUCCESS)
    {
        ULONG *pul = (ULONG *)&encaps;
        status = NDIS_STATUS_INVALID_PARAMETER;
        DPrintf(1, "[%s] %08lX, %08lX, %08lX, %08lX, %08lX, %08lX, %08lX\n", __FUNCTION__,
                pul[0],pul[1],pul[2],pul[3],pul[4],pul[5],pul[6]);
        if (encaps.Header.Size == sizeof(encaps) &&
            encaps.Header.Revision == NDIS_OFFLOAD_ENCAPSULATION_REVISION_1 &&
            encaps.Header.Type == NDIS_OBJECT_TYPE_OFFLOAD_ENCAPSULATION &&
            (encaps.IPv4.Enabled != NDIS_OFFLOAD_SET_ON || (encaps.IPv4.EncapsulationType & NDIS_ENCAPSULATION_IEEE_802_3)) &&
            (encaps.IPv6.Enabled != NDIS_OFFLOAD_SET_ON || (encaps.IPv6.EncapsulationType & NDIS_ENCAPSULATION_IEEE_802_3))
            )
         {
            DPrintf(0, "[%s] V4 types 0x%lX, header %d, enabled %d\n", __FUNCTION__,
                encaps.IPv4.EncapsulationType,
                encaps.IPv4.HeaderSize,
                encaps.IPv4.Enabled);
            DPrintf(0, "[%s] V6 types 0x%lX, header %d, enabled %d\n", __FUNCTION__,
                encaps.IPv6.EncapsulationType,
                encaps.IPv6.HeaderSize,
                encaps.IPv6.Enabled);

            if (encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_ON && encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_ON &&
                encaps.IPv6.HeaderSize == encaps.IPv4.HeaderSize)
            {
                pContext->Offload.ipHeaderOffset = encaps.IPv4.HeaderSize;
                pContext->bOffloadv4Enabled = TRUE;
                pContext->bOffloadv6Enabled = TRUE;
                status = NDIS_STATUS_SUCCESS;
            }
            else if (encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_OFF && encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_ON)
            {
                pContext->bOffloadv4Enabled = FALSE;
                pContext->bOffloadv6Enabled = TRUE;
                pContext->Offload.ipHeaderOffset = encaps.IPv6.HeaderSize;
                status = NDIS_STATUS_SUCCESS;
            }
            else if (encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_OFF && encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_ON)
            {
                pContext->bOffloadv4Enabled = TRUE;
                pContext->bOffloadv6Enabled = FALSE;
                pContext->Offload.ipHeaderOffset = encaps.IPv4.HeaderSize;
                status = NDIS_STATUS_SUCCESS;
            }
            else if (encaps.IPv4.Enabled == NDIS_OFFLOAD_SET_OFF && encaps.IPv6.Enabled == NDIS_OFFLOAD_SET_OFF)
            {
                pContext->bOffloadv4Enabled = FALSE;
                pContext->bOffloadv6Enabled = FALSE;
                status = NDIS_STATUS_SUCCESS;
            }
         }
    }
    return status;
}

/*******************************************************************
Provides startup information about offload capabilities and settings
********************************************************************/
NDIS_STATUS ParaNdis6_GetRegistrationOffloadInfo(
        PARANDIS_ADAPTER *pContext,
        NDIS_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES *poa)
{
    NDIS_STATUS  status = NDIS_STATUS_NOT_SUPPORTED;
    NdisZeroMemory(poa, sizeof(*poa));
    /* something supported? */
    if (pContext->Offload.flagsValue)
    {
        poa->Header.Type = NDIS_OBJECT_TYPE_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES;
        poa->Header.Revision = NDIS_MINIPORT_ADAPTER_OFFLOAD_ATTRIBUTES_REVISION_1;
        poa->Header.Size = sizeof(*poa);
        poa->DefaultOffloadConfiguration = &pContext->ReportedOffloadConfiguration;
        poa->HardwareOffloadCapabilities = &pContext->ReportedOffloadCapabilities;
        DumpOffloadStructure(poa->HardwareOffloadCapabilities, "Initial Capabilities");
        DumpOffloadStructure(poa->DefaultOffloadConfiguration, "Initial Configuration");
        status = NDIS_STATUS_SUCCESS;
    }
    return status;
}

#if NDIS_SUPPORT_NDIS620

void ParaNdis6_Fill620PowerCapabilities(PNDIS_PM_CAPABILITIES pPower620Caps)
{
    NdisZeroMemory(pPower620Caps, sizeof(*pPower620Caps));
    pPower620Caps->Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
    pPower620Caps->Header.Revision = NDIS_PM_CAPABILITIES_REVISION_1;
    pPower620Caps->Header.Size = NDIS_SIZEOF_NDIS_PM_CAPABILITIES_REVISION_1;

    // part of WOL support
    pPower620Caps->SupportedWoLPacketPatterns = 0;
    pPower620Caps->NumTotalWoLPatterns = 0;
    pPower620Caps->MaxWoLPatternSize = 0;
    pPower620Caps->MaxWoLPatternOffset = 0;
    pPower620Caps->MaxWoLPacketSaveBuffer = 0;

    // part of protocol offload support (ARP, NS IPv6)
    pPower620Caps->SupportedProtocolOffloads = 0;
    pPower620Caps->NumArpOffloadIPv4Addresses = 0;
    pPower620Caps->NumNSOffloadIPv6Addresses = 0;

    // if wake on magic packet supported
    pPower620Caps->MinMagicPacketWakeUp =
        (pPower620Caps->SupportedWoLPacketPatterns & NDIS_PM_WOL_MAGIC_PACKET_SUPPORTED) ?
        NdisDeviceStateD3 : NdisDeviceStateUnspecified;

    // if wake on link change supported
    pPower620Caps->MinLinkChangeWakeUp = NdisDeviceStateUnspecified;

    // if wake on pattern supported
    pPower620Caps->MinPatternWakeUp =
        (pPower620Caps->SupportedWoLPacketPatterns & ~NDIS_PM_WOL_MAGIC_PACKET_SUPPORTED) ?
        NdisDeviceStateD3 : NdisDeviceStateUnspecified;
}
#endif

NDIS_STATUS OnSetLinkParameters(PARANDIS_ADAPTER *pContext, tOidDesc *pOid)
{
    NDIS_LINK_PARAMETERS params;
    NDIS_STATUS status;

    UNREFERENCED_PARAMETER(pContext);

    status = ParaNdis_OidSetCopy(pOid, &params, sizeof(params));
    if (status == NDIS_STATUS_SUCCESS)
    {
        status = NDIS_STATUS_NOT_ACCEPTED;
        DPrintf(0, "[%s] requested:\n", __FUNCTION__);
        DPrintf(0, "Tx speed 0x%llx, Rx speed 0x%llx\n", params.XmitLinkSpeed, params.RcvLinkSpeed);
        DPrintf(0, "Duplex %d, PauseFn %d, AutoNeg 0x%X\n",
            params.MediaDuplexState, params.PauseFunctions, params.AutoNegotiationFlags);
    }
    return status;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>ro.pub.cs.aipi.lab01</groupId>
    <artifactId>01-BookStore-JDBC</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.4</version>
          <scope>test</scope>
        </dependency>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.37</version>
        </dependency>
    </dependencies>
</project>

redpajama_set_name: RedPajamaGithub


text:
var Path = require('path');
var pify = require('util').promisify;
var mkdirp = pify(require('mkdirp'));
var semverRegex = require('semver-regex');
var rimraf = pify(require('rimraf'));
var debug = require('debug')('pageboard:core');
var postinstall = require('postinstall');

var fs = {
	writeFile: pify(require('fs').writeFile),
	readFile: pify(require('fs').readFile),
	readdir: pify(require('fs').readdir),
	stat: pify(require('fs').stat),
	lstat: pify(require('fs').lstat),
	unlink: pify(require('fs').unlink),
	symlink: pify(require('fs').symlink)
};

exports.install = function(site, opt) {
	if (!site.data.module) {
		console.info("site has no module");
		return getPkg();
	}
	var dataDir = Path.join(opt.dirs.data, 'sites');

	return decideInstall(dataDir, site).then(function(pkg) {
		if (pkg.install) {
			return doInstall(site, pkg, opt);
		} else {
			console.info("skipped installation of:", site.data.module, site.data.version);
			return pkg;
		}
	}).then(function(pkg) {
		return populatePkg(site, pkg);
	});
};

exports.config = function(moduleDir, id, module, config) {
	debug("Module directory", module, moduleDir);
	return fs.readFile(Path.join(moduleDir, 'package.json')).then(function(buf) {
		var meta = JSON.parse(buf);
		var modOpts = meta.pageboard;
		if (!modOpts) {
			return true; // nothing to do
		} else if (modOpts === true) {
			modOpts = {};
		}

		var dstDir = id != 'pageboard' ? Path.join('/', '.files', id, module) : '/.' + id;
		var directories = modOpts.directories || [];
		if (!Array.isArray(directories)) directories = [directories];
		debug("processing directories from", moduleDir, directories);
		directories.forEach(function(mount) {
			if (typeof mount == "string") mount = {
				from: mount,
				to: mount
			};
			var from = Path.resolve(moduleDir, mount.from);
			if (from.startsWith(moduleDir) == false) {
				console.warn(`Warning: ${id} dependency ${module} bad mount from: ${from}`);
				return;
			}
			var to = Path.resolve(dstDir, mount.to);
			if (to.startsWith(dstDir) == false) {
				console.warn(`Warning: ${id} dependency ${module} bad mount to: ${to}`);
				return;
			}
			config.directories.push({
				from: from,
				to: to,
				priority: modOpts.priority || 0
			});
		});

		var elements = modOpts.elements || [];
		if (!Array.isArray(elements)) elements = [elements];
		debug("processing elements from", moduleDir, elements);
		return Promise.all(elements.map(function(path) {
			var absPath = Path.resolve(moduleDir, path);
			return fs.stat(absPath).then(function(stat) {
				if (stat.isDirectory()) return fs.readdir(absPath).then(function(paths) {
					// make sure files are ordered by basename
					paths.sort(function(a, b) {
						a = Path.basename(a, Path.extname(a));
						b = Path.basename(b, Path.extname(b));
						if (a == b) return 0;
						else if (a > b) return 1;
						else if (a < b) return -1;
					});
					return paths.map(function(path) {
						return Path.join(absPath, path);
					});
				});
				else return [absPath];
			}).then(function(paths) {
				paths.forEach(function(path) {
					if (path.endsWith('.js')) {
						config.elements.push({
							path: path,
							priority: modOpts.priority || 0
						});
					}
				});
			});
		}));
	}).catch(function(err) {
		console.error(`Error: ${id} dependency ${module} cannot be extracted`, err);
		return true;
	}).then(function(not) {
		if (id != "pageboard" || not === true) return;
		return module;
	});
};

exports.clean = function(site, pkg, opt) {
	var rootSite = Path.join(opt.dirs.data, 'sites', site.id);
	return fs.readdir(rootSite).then(function(paths) {
		return Promise.all(paths.map(function(path) {
			path = Path.join(rootSite, path);
			return fs.stat(path).then(function(stat) {
				return {stat, path};
			});
		})).then(function(stats) {
			stats.sort(function(a, b) {
				if (a.path == pkg.dir) return -1;
				if (a.stat.mtimeMs > b.stat.mtimeMs) return -1;
				if (a.stat.mtimeMs == b.stat.mtimeMs) return 0;
				if (a.stat.mtimeMs < b.stat.mtimeMs) return 1;
			});
			return Promise.all(stats.slice(2).map(function(obj) {
				return rimraf(obj.path);
			}));
		});
	}).catch(function(err) {
		console.error(err);
	}).then(function() {
		return pkg;
	});
};

function decideInstall(dataDir, site) {
	var version = site.data.version;
	if (version == "") version = site.data.version = null; // temporary fix, should not happen
	if (version == null) {
		version = "master";
	} else if (/\s/.test(version) == true || semverRegex().test(version) == false && /^\w+$/.test(version) == false) {
		return Promise.reject(new Error(`${site.id} has invalid version ${version}`));
	}
	var siteDir = Path.join(dataDir, site.id, version);

	return getPkg(siteDir).then(function(pkg) {
		if (pkg.name == null) {
			pkg.install = true;
			return pkg;
		}
		if (site.data.version == null) {
			// something is installed
			// if you want to update call site.save data.version...
			return pkg;
		}
		var siteModuleDir = Path.join(siteDir, 'node_modules', pkg.name);
		return fs.lstat(siteModuleDir).catch(function() {}).then(function(stat) {
			if (stat && stat.isSymbolicLink()) {
				console.warn("detected linked module", pkg.name);
			} else if (pkg.version == null || pkg.version != site.data.version) {
				pkg.install = true;
			}
			return pkg;
		});
	});
}

function doInstall(site, pkg, opt) {
	return prepareDir(pkg).then(function() {
		var version = site.data.version;
		var module = site.data.module;
		if (version != null) {
			if (module.indexOf('/') > 0 && !module.startsWith('@')) module += "#";
			else module += "@";
			module += version;
		}
		console.info("install", site.id, module, version);
		var baseEnv = {
			HOME: process.env.HOME,
			PATH: process.env.PATH
		};
		if (opt.env == "development" && process.env.SSH_AUTH_SOCK) {
			// some local setup require to pass this to be able to use ssh keys
			baseEnv.SSH_AUTH_SOCK = process.env.SSH_AUTH_SOCK;
		}
		if (opt.core.installer == "yarn") {
			return All.utils.spawn(opt.installerPath, [
				"--ignore-scripts", // only postinstall scripts are allowed through hook
				"--non-interactive", // yarn only
				"--ignore-optional", // yarn
				"--no-progress",
				"--production",
				"--no-lockfile", // yarn
				"--silent",
				"add", module
			], {
				cwd: pkg.dir,
				timeout: 60 * 1000,
				env: baseEnv
			});
		} else {
			return All.utils.spawn(opt.installerPath, [
				"install",
				"--ignore-scripts", // only postinstall scripts are allowed through hook
				"--no-optional", // npm
				"--no-progress",
				"--production",
				"--no-package-lock", // npm
				"--silent",
				"--no-audit",
				"--save", module
			], {
				cwd: pkg.dir,
				timeout: 60 * 1000,
				env: Object.assign(baseEnv, {
					npm_config_userconfig: '' // attempt to disable user config
				})
			});
		}
	}).then(function(out) {
		if (out) debug(out);
	}).catch(function(err) {
		if (typeof err == "string") {
			var installError = new Error(err);
			installError.name = "InstallationError";
			err = installError;
			delete err.stack;
		}
		throw err;
	}).then(function() {
		return getPkg(pkg.dir).then(function(npkg) {
			if (!npkg.name) {
				var err = new Error("Installation error");
				err.output = out;
				throw err;
			}
			return npkg;
		}).then(function(pkg) {
			return runPostinstall(pkg.dir, pkg.name, opt).then(function(result) {
				if (result) debug(result);
				return pkg;
			});
		});
	});
}

function prepareDir(pkg) {
	return mkdirp(pkg.dir).then(function() {
		return fs.writeFile(pkg.path, JSON.stringify({
			"private": true,
			"dependencies": {} // installation of main module populates it for us
		}));
	});
}

function populatePkg(site, pkg) {
	var version = pkg.version != null ? pkg.version : site.data.version != null ? site.data.version : 'master';
	var pair = `${site.id}/${version}`;
	var siteModuleDir = Path.join(pkg.dir, 'node_modules', pkg.name);
	return fs.readFile(Path.join(siteModuleDir, "package.json")).then(function(buf) {
		return JSON.parse(buf.toString());
	}).then(function(sitePkg) {
		// configure directories/elements for each dependency
		return Promise.all(Object.keys(sitePkg.dependencies || {}).map(function(subModule) {
			var moduleDir = Path.join(pkg.dir, 'node_modules', subModule);
			return exports.config(moduleDir, pair, subModule, pkg);
		})).then(function() {
			// configure directories/elements for the module itself (so it can
			// overrides what the dependencies have installed
			return exports.config(siteModuleDir, pair, pkg.name, pkg);
		});
	}).then(function() {
		return pkg;
	});
}

function getPkg(pkgDir) {
	var pkgPath = pkgDir != null ? Path.join(pkgDir, 'package.json') : null;
	var pkg = {
		dir: pkgDir,
		path: pkgPath,
		directories: [],
		elements: []
	};
	if (pkgDir == null) return Promise.resolve(pkg);
	return fs.readFile(pkgPath).then(function(buf) {
		var obj = JSON.parse(buf.toString());
		var deps = Object.keys(obj.dependencies);
		if (!deps.length) return pkg;
		// if siteModule is a github url, version will be <siteModule>#hash
		// if siteModule is a real package, version is a real version
		var name = deps[0];
		var version = obj.dependencies[name];
		if (version.indexOf('#') > 0) version = version.split('#').pop();
		// version is a string here so this boolean check is all right
		if (!version || version.indexOf('/') >= 0) version = null;
		pkg.name = name;
		if (version != null) pkg.version = version;
		return pkg;
	}).catch(function() {
		return pkg;
	});
}

function getDependencies(root, name, list, deps) {
	if (!deps) deps = {};
	var dir = Path.join(root, 'node_modules', name);
	if (deps[dir]) return;
	return fs.readFile(Path.join(dir, 'package.json')).catch(function(err) {
		// nested dep
	}).then(function(buf) {
		if (!buf || deps[dir]) return;
		deps[dir] = true;
		var pkg = JSON.parse(buf);
		var pst = (pkg.scripts && pkg.scripts.postinstall || "").split(' ');
		if (pst.includes("postinstall")) {
			list.push({pkg, dir});
		}
		return Promise.all(Object.keys(pkg.dependencies || {}).map(function(name) {
			return getDependencies(root, name, list, deps);
		}));
	});
}

function runPostinstall(dir, name, opt) {
	var list = [];
	return getDependencies(dir, name, list).then(function() {
		return Promise.all(list.reverse().map(function({pkg, dir}) {
			return postinstall.process(pkg.postinstall, {
				cwd: dir,
				allow: opt.postinstall || [
					'link',
					'copy',
					'concat',
					'js',
					'css',
					'browserify'
				]
			});
		}));
	});
}


text:
package japsadev.xm.genome;

/**
 *
 */

import japsa.util.IntIterator;

import java.util.Random;

public class MyBigHashtableLong {// implements PatternStore{

	public Random rnd = new Random(1);
	int hashSize;
	int numSeqs;

	/**
	 * Maximum capacity as of in HashMap class
	 */
	static final int MAXIMUM_CAPACITY = 1 << 30;
	static final int INITIAL_CELL_CAPACITY = 16;

	// private int hashSize;
	private int currentKey = 0;
	private int psuedoPalinKey = 0;

	// values[key][seqID][posSrc]
	private int[][][] values;

	// valueCount[key][seqID]
	private int[][] valueCount;
	private int _usableBitMask = 0;

	protected int _bitPerSymbol = 2;// For DNA, for protein must be 5
	protected int complement; // == largest base complement(x) = complement - x.
								// In case of dna, complement = 3

	private long alloc = 0, used = 0, reallo = 0, init = 0;
	protected int preCompute;
	private MyBigHashLongIterator copyIter = null;

	// A dummy one, should not call this
	protected MyBigHashtableLong() {

	}

	public MyBigHashtableLong(int nSeqs, int hashSize) {
		this(nSeqs, hashSize, 2);
	}

	public MyBigHashtableLong(int nSeqs, int hashSize, int bpp) {
		this.numSeqs = nSeqs;
		copyIter = new MyBigHashLongIterator();
		initilise(hashSize, bpp);
	}

	public void initilise() {
		initilise(hashSize, _bitPerSymbol);
	}

	public void initilise(int hSize, int bpp) {
		this.hashSize = hSize;
		// Inililise usable bit mask
		_bitPerSymbol = bpp;

		complement = (byte) ((1 << bpp) - 1);// 1 << 2 - 1 = 3

		for (int i = 0; i < hashSize * _bitPerSymbol; i++) {
			_usableBitMask <<= 1;
			_usableBitMask |= 1; // same as ++
		}// assert _usableBitMask = 11..11: hashSize * _bitPerSymbol bit

		preCompute = (_bitPerSymbol * (hashSize - 1));

		clear();
	}

	public void clear() {
		// Create an array of entries
		long s1 = System.currentTimeMillis();
		valueCount = new int[1 << (_bitPerSymbol * hashSize)][numSeqs];
		values = new int[valueCount.length][numSeqs][];
		long s2 = System.currentTimeMillis();

		System.out.println((s2 - s1) + "=============");

		// Set all count to -1
		for (int x = 0; x < valueCount.length; x++) {
			for (int y = 0; y < numSeqs; y++)
				valueCount[x][y] = -1;
		}
	}

	public void reinitialise_optimise() {
		// Create an array of entries
		for (int x = 0; x < valueCount.length; x++) {
			for (int y = 0; y < numSeqs; y++) {
				valueCount[x][y]++;
				if (valueCount[x][y] > 0) {
					values[x][y] = new int[valueCount[x][y]];
					alloc += values[x][y].length;
					init++;
				}
				valueCount[x][y] = 0;
			}
		}
		this.currentKey = this.psuedoPalinKey = 0;
	}

	public void initiliseCurrentValue() {
		for (int y = 0; y < numSeqs; y++)
			initiliseValue(currentKey, y);
	}

	/**
	 * Only call when the key has not been initilised
	 *
	 * @param key
	 * @param sid
	 */
	public void initiliseValue(int key, int sid) {
		values[key][sid] = new int[INITIAL_CELL_CAPACITY];
		valueCount[key][sid] = 0;

		alloc += INITIAL_CELL_CAPACITY;
		init++;
	}

	/**
	 * Compute the new key as a new base is read in
	 *
	 * @param baseInd
	 */

	public void nextKey(int baseInd) {
		// currentKey = currentKey x
		currentKey <<= _bitPerSymbol;
		currentKey &= _usableBitMask;
		currentKey |= baseInd;// same as + baseInd

		psuedoPalinKey >>= _bitPerSymbol;
		// baseInd = ;
		psuedoPalinKey |= (complement - baseInd) << preCompute;// (_bitPerSymbol
																// * (hashSize
																// -1));

	}

	/**
	 * Put a number into the hash table at the current key
	 *
	 * @param val
	 */
	public void putCurrentValue_psuedo(int sid, int val) {
		valueCount[currentKey][sid]++;
	}

	public void printMemoryNeeded() {
		long sum = 0;
		for (int i = 0; i < valueCount.length; i++) {
			for (int y = 0; y < numSeqs; y++)
				if (valueCount[i][y] >= 0) {
					sum += (valueCount[i][y] + 1);
				}
		}
		System.out.println(valueCount.length + " arrays of total " + sum);
	}

	/**
	 * Put a number into the hash table at the current key
	 *
	 * @param val
	 */
	public void putCurrentValue(int sid, int val) {
		if (valueCount[currentKey][sid] < 0) {
			initiliseValue(currentKey, sid);
			// initiliseCurrentValue();
		}

		putValue(val, currentKey, sid);
	}

	public void putValue(int val, int key, int sid) {
		// invariat valueCount[key] = values[key].length
		if (valueCount[key][sid] == values[key][sid].length) {
			// If no the array is full, reallocate array, doule size
			// int newArray[] = new int[values[key].length << 1];
			int newArray[] = new int[(int) (values[key][sid].length * 1.5)];
			System.arraycopy(values[key][sid], 0, newArray, 0,
					values[key][sid].length);

			alloc += newArray.length;
			alloc -= values[key].length;

			reallo++;

			values[key][sid] = newArray;
		}
		values[key][sid][valueCount[key][sid]] = val;
		valueCount[key][sid]++;

		used++;
	}

	// ///////////////////////////////////////////
	/**
	 * Return the size of the current hash value
	 *
	 * @return
	 */
	// public int getCurrentCount(){
	// return valueCount[currentKey];
	// }

	// public int getCount(int key){
	// return valueCount[key];
	// }
	/**
	 * Return the current key
	 *
	 * @return
	 */
	public int getCurrentKey() {
		return currentKey;
	}

	public void setCurrentKey(int key) {
		this.currentKey = key;
	}

	public int getPsuedoPalinKey() {
		return psuedoPalinKey;
	}

	public void setPsuedoPalinKey(int psuedoPalinKey) {
		this.psuedoPalinKey = psuedoPalinKey;
	}

	public void printSummary() {
		System.out
				.printf(" Init %d(%d), reallocation %d, Allocatate %d, used %d, (%.2f %% )\n",
						init, valueCount.length, reallo, alloc, used,
						(used * 100.0 / alloc));
	}

	public MyBigHashLongIterator iterator() {
		copyIter.reset();
		return copyIter;
	}

	public static void main(String[] args) {
		// MyBigHashtableLong myhash = new MyBigHashtableLong(5,2);

		// for ( int i = 0; i < 100; i++){
		// myhash.nextKey((byte)(i % 4));
		// myhash.putCurrentValue(i);
		// System.out.println();
		// }
	}

	public int hashSize() {
		return hashSize;
	}

	class MyBigHashLongIterator implements IntIterator {

		// v[sid][posSrc]
		int[][] copies;// = new int[2 * numSeqs][];
		int[] totals;// totals for all

		int total;// total number of posSrc

		boolean isPalin = false;
		int sid;

		public MyBigHashLongIterator() {
			copies = new int[2 * numSeqs][];
			totals = new int[2 * numSeqs];
		}

		/**
		 * Set an array of arrays
		 */
		public void reset() {
			total = 0;
			for (int y = 0; y < numSeqs; y++) {
				copies[y] = values[currentKey][y];
				totals[y] = valueCount[currentKey][y];

				if (totals[y] < 0)
					totals[y] = 0;

				total += totals[y];

				copies[y + numSeqs] = values[psuedoPalinKey][y];
				totals[y + numSeqs] = valueCount[psuedoPalinKey][y];
				if (totals[y + numSeqs] < 0)
					totals[y + numSeqs] = 0;
				total += totals[y + numSeqs];
			}
		}

		public boolean isPalin() {
			return isPalin;
		}

		public int sequenceID() {
			return 0;
		}

		public boolean hasNext() {
			return total > 0;
			// return cIter.hasNext() || pIter.hasNext();
		}

		public int sizeAvailable() {
			return total;
			// return cIter.total + pIter.total;
		}

		public int next() {
			int random_index = rnd.nextInt(total);

			sid = 0;
			while (random_index >= totals[sid]) {
				random_index -= totals[sid];
				sid++;
			}

			// assert: accTotal < randomIndex

			int[] myArray = copies[sid];

			totals[sid]--;
			int myTotal = totals[sid];// point to the last availble

			if (random_index < myTotal) {// Move the expert selected to end of
											// the list
				// so wont be selected again
				int tmp = myArray[random_index];
				myArray[random_index] = myArray[myTotal];
				myArray[myTotal] = tmp;
			}// else random_index +1 == total

			if (sid < numSeqs) {
				isPalin = false;
			} else {
				isPalin = true;
				sid -= numSeqs;
			}

			total--;
			return myArray[myTotal];

		}
	}

}


text:
package com.treasure_data.model;

public class DeleteTableResult extends TableSpecifyResult<Table> {

    public DeleteTableResult(Database database, String tableName) {
        super(new Table(database, tableName));
    }
}


text:
A [Sublime Text](http://www.sublimetext.com/) package for the [Swift programming language](https://developer.apple.com/swift/)

## Installation

### via Package Control (Recommended)
[Package Control](http://wbond.net/sublime_packages/package_control) is a package manager for Sublime Text 2 & 3.  If you don't already have it installed, follow the [installation instructions here](https://sublime.wbond.net/installation).

Once Package Control is installed, restart Sublime and follow these steps:
* Open the Command Pallette (`cmd + shift + p` on OS X / Linux or `ctrl + shift + p` on Windows)
* Type "install" and select "Package Control: Install Package"
* Type "swift" and press Enter

All done! Package Control will automatically update the package whenever there's a new version.

## License

The MIT License (MIT)

Copyright (c) 2014 Matthew Alexander <matt@queg.net>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
<?php

class UploadController extends BaseController{

	private $g;

	public function __construct(Google_Service $ga)
    {
        $this->g = $ga;
    }

	public function insertFile()
	{
		$service = $this->g->getService();
  		$file = new Google_Service_Drive_DriveFile();
  		$file->setTitle('My document');
		$file->setDescription('A test document');
		$file->setMimeType('text/plain');

  		// Set the parent folder.
  		/*if ($parentId != null)
  		{
    		$parent = new Google_ParentReference();
    		$parent->setId($parentId);
    		$file->setParents(array($parent));
  		}*/

  		try {
    		$data = file_get_contents('C:\Users\Pepito\Desktop\upload.txt');

			$createdFile = $service->files->insert($file, array(
      		'data' => $data,
      		'mimeType' => 'text/plain',
      		'uploadType' => 'multipart'
    		));

    	// Uncomment the following line to print the File ID
    	print_r($createdFile);

    		//return $createdFile;
  		} catch (Exception $e) {
    		print "An error occurred: " . $e->getMessage();
  		}
	}
}


text:
.tif-destination.ng-enter,
.tif-destination.ng-leave,
.tif-destination.ng-move {
  -webkit-transition: 0.5s linear all;
  -moz-transition: 0.5s linear all;
  -o-transition: 0.5s linear all;
  transition: 0.5s linear all;
}

.tif-destination.ng-enter,
.tif-destination.ng-move {
  opacity: 0;
  overflow: hidden;
}

.tif-destination.ng-move.ng-move-active,
.tif-destination.ng-enter.ng-enter-active {
  opacity: 1;
}

.tif-destination.ng-leave {
  opacity: 1;
  overflow: hidden;
}

.tif-destination.ng-leave.ng-leave-active {
  opacity: 0;
  padding-top: 0;
  padding-bottom: 0;
}


text:
package org.elasticsearch.index.analysis;

import org.elasticsearch.Version;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.indices.analysis.AnalysisModule;
import org.elasticsearch.plugins.AnalysisPlugin;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.IndexSettingsModule;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;

public class AnalysisTestsHelper {

    public static ESTestCase.TestAnalysis createTestAnalysisFromClassPath(
        final Path baseDir,
        final String resource,
        final AnalysisPlugin... plugins
    ) throws IOException {
        final Settings settings = Settings.builder()
            .loadFromStream(resource, AnalysisTestsHelper.class.getResourceAsStream(resource), false)
            .put(Environment.PATH_HOME_SETTING.getKey(), baseDir.toString())
            .build();

        return createTestAnalysisFromSettings(settings, plugins);
    }

    public static ESTestCase.TestAnalysis createTestAnalysisFromSettings(final Settings settings, final AnalysisPlugin... plugins)
        throws IOException {
        return createTestAnalysisFromSettings(settings, null, plugins);
    }

    public static ESTestCase.TestAnalysis createTestAnalysisFromSettings(
        final Settings settings,
        final Path configPath,
        final AnalysisPlugin... plugins
    ) throws IOException {
        final Settings actualSettings;
        if (settings.get(IndexMetadata.SETTING_VERSION_CREATED) == null) {
            actualSettings = Settings.builder().put(settings).put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).build();
        } else {
            actualSettings = settings;
        }
        final IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("test", actualSettings);
        final AnalysisRegistry analysisRegistry = new AnalysisModule(new Environment(actualSettings, configPath), Arrays.asList(plugins))
            .getAnalysisRegistry();
        return new ESTestCase.TestAnalysis(
            analysisRegistry.build(indexSettings),
            analysisRegistry.buildTokenFilterFactories(indexSettings),
            analysisRegistry.buildTokenizerFactories(indexSettings),
            analysisRegistry.buildCharFilterFactories(indexSettings)
        );
    }

}


text:
#ifndef OPENTISSUE_CORE_MATH_INTERVAL_BOOST_INTERVAL_TYPE_TRAITS_H
#define OPENTISSUE_CORE_MATH_INTERVAL_BOOST_INTERVAL_TYPE_TRAITS_H
//
// OpenTissue Template Library
// - A generic toolbox for physics-based modeling and simulation.
// Copyright (C) 2008 Department of Computer Science, University of Copenhagen.
//
// OTTL is licensed under zlib: http://opensource.org/licenses/zlib-license.php
//
#include <OpenTissue/configuration.h>

#include <OpenTissue/core/math/interval/io/boost_interval_io.h>
#include <OpenTissue/core/math/interval/interval_vector.h>
#include <OpenTissue/core/math/interval/interval_matrix.h>

#include <boost/numeric/interval.hpp>

namespace OpenTissue
{
  namespace math
  {
    namespace interval
    {

      /**
      * Boost Interval Fixed Type Traits.
      * This class provides easy type handling of the boost interval class
      *
      *   http://www.boost.org/libs/numeric/interval/doc/interval.htm
      *
      * In computer graphics, we really do not need all the safety we
      * get from the default interval type:
      *
      *    typedef  ... real_type;
      *    typedef boost::numeric::interval<real_type>  interval_type;
      *
      * This class tweaks the policies of the interval class inorder to sacrifice
      * everything for the need for speed.
      *
      * According to
      *
      *   http://www.boost.org/libs/numeric/interval/doc/rounding.htm#perf
      *
      * It reads:
      *
      *   ``for fast wide intervals without any rounding nor precision, use save_state_nothing<rounded_transc_exact<T>  >;''
      *
      * From
      *
      *   http://www.boost.org/libs/numeric/interval/doc/checking.htm
      *
      * We have:
      *
      *  ``If you do not mind having undefined results when an empty interval
      *    or an interval number is produced, your best bet is to create your
      *    own policy by overloading checking_base and modifying is_nan et is_empty
      *    in order for them to always return false. It is probably the fastest
      *    checking policy available; however, it suffers from its deficient
      *    security.''
      *
      * From these we have created our own rounding and checking policies. This
      * class provides an easy way to extract the interval type for this
      * ``speed optimized'' interval usage:
      *
      *  #include <OpenTissue/core/math/interval/interval_boost_interval_type_traits.h>
      *
      *  typedef BoostIntervalTypeTraits<double>::interval_type interval_type;
      *
      *   ....
      *
      * Initial testings (see interval demo application) With .NET 2005 C++ compiler,
      * this fast boost interval type outruns the OpenTissue interval type by a factor
      * of 2. With gcc it seems that OpenTissue interval type is capable of
      * beating boost. However, this fast boost type comes pretty close to the
      * OpenTissue type on gcc.
      *
      * Our (Henrik Dohlann and Kenny Erleben) recommendations: Use this fast boost interval
      * type if you do not need the gcc-cutting edge.
      *
      *  Sometimes it is possible to add further optimizations by adding the
      *  following code around interval ``intensive blocks''
      *
      *    typedef .... interval_type;
      *    // save and initialize the rounding mode
      *    interval_type::traits_type::rounding rnd;
      *    // define the unprotected version of the interval type
      *    typedef  boost::numeric::interval_lib::unprotect<interval_type>::type interval_type2;
      *
      * Now one should use interval_type2 in the following computaiton block. In our test runs
      * this ``unprotect'' tweak did not add a lot of performance to the fast boost interval type
      * this class provides. Thus we recommend only using the ``unprotect''-way if the default
      * boost interval type is used.
      */
      template<typename T>
      class BoostIntervalTypeTraits
      {
      protected:

        template<typename T2>
        struct raw_checking : public boost::numeric::interval_lib::checking_base<T2>
        {
          static bool is_nan(const T2&) { return false; }
          static bool is_empty(const T2&, const T2&){ return false; }
        };

        typedef raw_checking<T> checking_type;
        typedef boost::numeric::interval_lib::save_state_nothing< boost::numeric::interval_lib::rounded_arith_exact<T> > rounding_type;
        typedef boost::numeric::interval_lib::policies< rounding_type, checking_type > policy_type;

      public:

        typedef boost::numeric::interval<T >                   default_interval_type;
        typedef boost::numeric::interval<T, policy_type >      interval_type;          ///< Fast interval type, but do not have any rounding, precision or checking policies worth of mentioning. If you use this then you should know what you are doing.

      };

    } // namespace interval
  } // namespace math
} // namespace OpenTissue

// OPENTISSUE_CORE_MATH_INTERVAL_BOOST_INTERVAL_TYPE_TRAITS_H
#endif


text:
"""
Copyright 2013 Steven Diamond

This file is part of CVXPY.

CVXPY is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

CVXPY is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with CVXPY.  If not, see <http://www.gnu.org/licenses/>.
"""

from .constant import Constant
from .callback_param import CallbackParam
from .parameter import Parameter


text:
/**
 * Created by sam on 15-2-12.
 */

exports.UserInfoDAL = require('./UserInfoDal');


text:
/* @flow */
import basic from './basic';
import disabled from './disabled';
import importSyntax from './importSyntax';
import rtl from './rtl';

export default [importSyntax, basic, disabled, rtl];


text:
package org.javaee7.cdi.bean.scopes;

import java.io.IOException;
import java.io.PrintWriter;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author arungup
 */
@WebServlet(urlPatterns = {"/ServerServlet"})
public class ServerServlet extends HttpServlet {

    @Inject MyRequestScopedBean requestBean;
    @Inject MyRequestScopedBean requestBean2;

    @Inject MySessionScopedBean sessionBean;
    @Inject MySessionScopedBean sessionBean2;

    @Inject MyApplicationScopedBean applicationBean;
    @Inject MySingletonScopedBean singletonBean;

    /**
     * Processes requests for both HTTP
     * GET and
     * POST methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try (PrintWriter out = response.getWriter()) {
            out.println("Request-scoped bean");
            out.println("

(1): " + requestBean.getID());
            out.println("
(2): " + requestBean2.getID());
            out.println("

Session-scoped bean");
            out.println("

(1): " + sessionBean.getID());
            out.println("
(2): " + sessionBean2.getID());
            out.println("

Application-scoped bean: " + applicationBean.getID());
            out.println("

Singleton-scoped bean: " + singletonBean.getID());
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * GET method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}