ipsec驱动源代码(部分)

时间:2022-12-09 16:31:12
免费第一个miniport.c

#include "precomp.h"
#include "pgpNetKernel.h"

#include "stdio.h"

#pragma hdrstop

BOOLEAN VpnAdapterCreated = FALSE;
extern UINT MediumArraySize;

NDIS_STATUS
MPInitialize(
OUT PNDIS_STATUS OpenErrorStatus,
OUT PUINT SelectedMediumIndex,
IN PNDIS_MEDIUM MediumArray,
IN UINT MediumArraySize,
IN NDIS_HANDLE MiniportAdapterHandle,
IN NDIS_HANDLE WrapperConfigurationContext
)
/*++

Routine Description:

This is the initialize handler which gets called as a result of
the BindAdapter handler calling NdisIMInitializeDeviceInstanceEx.
The context parameter which we pass there is the adapter structure
which we retrieve here.

Arguments:

OpenErrorStatus Not used by us.
SelectedMediumIndex Place-holder for what media we are using
MediumArray Array of ndis media passed down to us to pick from
MediumArraySize Size of the array
MiniportAdapterHandle The handle NDIS uses to refer to us
WrapperConfigurationContext For use by NdisOpenConfiguration

Return Value:

NDIS_STATUS_SUCCESS unless something goes wrong

--*/
{
UINT i;
PADAPT pAdapt;
NDIS_STATUS Status = NDIS_STATUS_FAILURE;
NDIS_MEDIUM Medium;
//add
PBINDING_CONTEXT bindingContext;
//end

UNREFERENCED_PARAMETER(WrapperConfigurationContext);

do
{
//
// Start off by retrieving our adapter context and storing
// the Miniport handle in it.
//
pAdapt = NdisIMGetDeviceContext(MiniportAdapterHandle);
pAdapt->MiniportHandle = MiniportAdapterHandle;

DBGPRINT(("==> Miniport Initialize: Adapt %p/n", pAdapt));

//
// Usually we export the medium type of the adapter below as our
// virtual miniport's medium type. However if the adapter below us
// is a WAN device, then we claim to be of medium type 802.3.
//
Medium = pAdapt->media;

if (Medium == NdisMediumWan)
{
Medium = NdisMedium802_3;
}

for (i = 0; i < MediumArraySize; i++)
{
if (MediumArray[i] == Medium)
{
*SelectedMediumIndex = i;
break;
}
}

if (i == MediumArraySize)
{
Status = NDIS_STATUS_UNSUPPORTED_MEDIA;
break;
}


//
// Set the attributes now. NDIS_ATTRIBUTE_DESERIALIZE enables us
// to make up-calls to NDIS without having to call NdisIMSwitchToMiniport
// or NdisIMQueueCallBack. This also forces us to protect our data using
// spinlocks where appropriate. Also in this case NDIS does not queue
// packets on our behalf. Since this is a very simple pass-thru
// miniport, we do not have a need to protect anything. However in
// a general case there will be a need to use per-adapter spin-locks
// for the packet queues at the very least.
//
NdisMSetAttributesEx(MiniportAdapterHandle,
pAdapt,
0, // CheckForHangTimeInSeconds
NDIS_ATTRIBUTE_BUS_MASTER | //add by hunter
NDIS_ATTRIBUTE_IGNORE_PACKET_TIMEOUT |
NDIS_ATTRIBUTE_IGNORE_REQUEST_TIMEOUT|
NDIS_ATTRIBUTE_INTERMEDIATE_DRIVER |
NDIS_ATTRIBUTE_DESERIALIZE |
NDIS_ATTRIBUTE_NO_HALT_ON_SUSPEND,
0);

//add
Status = NdisMAllocateMapRegisters(MiniportAdapterHandle,
NdisInterfaceInternal,
1,//NDIS_DMA_32_BITS
1,
0x1000
);

if (Status != NDIS_STATUS_SUCCESS)
return NDIS_STATUS_FAILURE;

pAdapt->SharedMemorySize = 1024*4; // Fix, should get from registry.
if (pAdapt->SharedMemorySize)
{
NdisMAllocateSharedMemory(MiniportAdapterHandle,
pAdapt->SharedMemorySize,
TRUE,
&pAdapt->SharedMemoryPtr,
&pAdapt->SharedMemoryPhysicalAddress
);
if (pAdapt->SharedMemoryPtr == NULL)
{
DBGPRINT(("!!!!! Could not allocate shared memory./n"));
}
else
{
DBGPRINT(("Allocate shared memory address is 0X%X./n",pAdapt->SharedMemoryPhysicalAddress));
NdisZeroMemory(pAdapt->SharedMemoryPtr,pAdapt->SharedMemorySize);
}
}

Status = AllocatePGPnetPacketPool(pAdapt);
if (Status != NDIS_STATUS_SUCCESS)
return NDIS_STATUS_FAILURE;

// InitializeListHead(&pAdapt->Bindings);

NdisInitializeTimer(&pAdapt->collection_timer,
FragmentCollection,
pAdapt);
/*
NdisInitializeTimer(&pAdapt->request_timer,
RequestTimerRoutine,
pAdapt);
*/
if (pAdapt->media == NdisMedium802_3 || pAdapt->media == NdisMediumWan)
pAdapt->eth_hdr_len = ETHER_HEADER_SIZE;

pAdapt->open = TRUE;
pAdapt->SendPackets = 0;
pAdapt->ReceivePackets = 0;

//这两个句柄可能设置不对,有可能没用
// pAdapt->MiniportHandle = BindContext;
// pAdapt->NdisAdapterRegistrationHandle = SystemSpecific1;

//该句柄是用来注册适配器和分配共享内存时使用的,在passthru里面
//没有对应的,在这里所有适配器句柄都沿用passthru的句柄,
//(除NdisAdapterRegistrationHandle之外),其他结构变量使用pgpnet的

InitializeListHead(&pAdapt->Bindings);

NdisAllocateMemoryWithTag(&bindingContext,
sizeof(BINDING_CONTEXT),
TAG
);

if (bindingContext == NULL)
{
Status = NDIS_STATUS_RESOURCES;
break;
}

NdisZeroMemory(bindingContext, sizeof(BINDING_CONTEXT));

//*MacBindingHandle = bindingContext;
bindingContext->NdisBindingContextFromProtocol = MiniportAdapterHandle;
bindingContext->adapter = pAdapt;

NdisAcquireSpinLock(&pAdapt->general_lock);
InsertTailList(&pAdapt->Bindings, &bindingContext->Next);
bindingContext->InstanceNumber = pAdapt->BindingNumber++;
NdisReleaseSpinLock(&pAdapt->general_lock);
NdisSetTimer(&pAdapt->collection_timer, 60000);
//end
//
// Initialize LastIndicatedStatus to be NDIS_STATUS_MEDIA_CONNECT
//
pAdapt->LastIndicatedStatus = NDIS_STATUS_MEDIA_CONNECT;

//
// Initialize the power states for both the lower binding (PTDeviceState)
// and our miniport edge to Powered On.
//
pAdapt->MPDeviceState = NdisDeviceStateD0;
pAdapt->PTDeviceState = NdisDeviceStateD0;

//
// Add this adapter to the global pAdapt List
//
NdisAcquireSpinLock(&GlobalLock);

pAdapt->Next = pAdaptList;
pAdaptList = pAdapt;

NdisReleaseSpinLock(&GlobalLock);

//
// Create an ioctl interface
//
(VOID)PtRegisterDevice();

Status = NDIS_STATUS_SUCCESS;
}
while (FALSE);

//
// If we had received an UnbindAdapter notification on the underlying
// adapter, we would have blocked that thread waiting for the IM Init
// process to complete. Wake up any such thread.
//
ASSERT(pAdapt->MiniportInitPending == TRUE);
pAdapt->MiniportInitPending = FALSE;
NdisSetEvent(&pAdapt->MiniportInitEvent);

DBGPRINT(("<== Miniport Initialize: Adapt %p, Status %x/n", pAdapt, Status));

*OpenErrorStatus = Status;

return Status;
}


NDIS_STATUS
MPSend(
IN NDIS_HANDLE MiniportAdapterContext,
IN PNDIS_PACKET Packet,
IN UINT Flags
)
/*++

Routine Description:

Send Packet handler. Either this or our SendPackets (array) handler is called
based on which one is enabled in our Miniport Characteristics.

Arguments:

MiniportAdapterContext Pointer to the adapter
Packet Packet to send
Flags Unused, passed down below

Return Value:

Return code from NdisSend

--*/
{
PADAPT pAdapt = (PADAPT)MiniportAdapterContext;
NDIS_STATUS Status;
PNDIS_PACKET MyPacket;
PVOID MediaSpecificInfo = NULL;
ULONG MediaSpecificInfoSize = 0;
//add0
// NDIS_STATUS status;
PBINDING_CONTEXT binding = NULL;
// PVPN_ADAPTER adapter;
PNDIS_BUFFER src_buffer;
UINT src_len;
PNDIS_BUFFER working_buffer;
PVOID working_block;
UINT working_block_len;

PETHERNET_HEADER eth_header;
USHORT eth_protocol;
USHORT eth_header_len;
PIP_HEADER ip_header;
PUDP_HEADER udp_header = 0;

PPGPNDIS_PACKET pgpPacket;
PPGPNDIS_PACKET_HEAD packetHead;

BOOLEAN newHead = FALSE;
PGPnetPMStatus pmstatus;
BOOLEAN assembleComplete = FALSE;

//add1
UINT j,len;
PUCHAR bBlock;
UCHAR hBuffer[1500] = "";

DBGPRINT(("MPSend function has been called.../n"));

//end0
//
// The driver should fail the send if the virtual miniport is in low
// power state
//

if (pAdapt->MPDeviceState > NdisDeviceStateD0)
{
return NDIS_STATUS_FAILURE;
}

NdisAcquireSpinLock(&pAdapt->general_lock);
if (pAdapt->PTDeviceState > NdisDeviceStateD0)
{
NdisReleaseSpinLock(&pAdapt->general_lock);
return NDIS_STATUS_FAILURE;

}
pAdapt->OutstandingSends++;
NdisReleaseSpinLock(&pAdapt->general_lock);

NdisQueryPacket(Packet, NULL, NULL, &src_buffer, &src_len);
NdisQueryBuffer(src_buffer, &working_block, &working_block_len);

eth_header = (PETHERNET_HEADER) working_block;
eth_protocol = *((PUSHORT)(ð_header->eth_protocolType[0]));
eth_header_len = sizeof(ETHERNET_HEADER);
if (eth_protocol != IPPROT_NET)
{
if (eth_protocol == ARPPROT_NET && pAdapt->media != NdisMediumWan)
{
DBGPRINT(( "GetIPAddressFromARP to be called/n" ));
GetIPAddressFromARP(pAdapt, (PVOID)((UCHAR*)eth_header + eth_header_len));
}
goto bailout;
}

if (BroadcastEthernetAddress(eth_header->eth_dstAddress))
goto bailout;

if (pAdapt->media != NdisMedium802_3 && pAdapt->media != NdisMediumWan)
{
Status = NDIS_STATUS_NOT_ACCEPTED;
goto failout;
}

if (working_block_len >= eth_header_len + sizeof(IP_HEADER))
{
ip_header = (PIP_HEADER) ( (PCHAR)working_block + eth_header_len);
working_block = (PCHAR)working_block + eth_header_len;
working_block_len -= eth_header_len;
}
else if (working_block_len == eth_header_len)
{

NdisGetNextBuffer(src_buffer, &working_buffer);
if (working_buffer == NULL)
{
Status = NDIS_STATUS_NOT_ACCEPTED;
goto failout;
}
NdisQueryBuffer(working_buffer, &working_block, &working_block_len);

ip_header = (PIP_HEADER)working_block;
}
else
{
Status = NDIS_STATUS_NOT_ACCEPTED;
goto failout;
}

if (ip_header->ip_prot == PROTOCOL_IGMP)
goto bailout;
//add
bBlock = (PUCHAR)ip_header;
if (bBlock[0] == 0X45 && bBlock[9] == 0X06)
{
DBGPRINT(("ip_header_len:0X%X/n",ntohs(ip_header->ip_len)));
DBGPRINT(("ip_header:/n"));
len = (ntohs(ip_header->ip_len)>500) ? 500 : ntohs(ip_header->ip_len);
for (j=0;j sprintf(hBuffer + (2+1)*j,"%2.2X ",bBlock[j]);
DBGPRINT(("%s/n",hBuffer));
}
//end
if (ip_header->ip_prot == PROTOCOL_UDP)
{
if( working_block_len <= sizeof(struct tag_IP_HEADER) ) // FIX!!! ONLY work for ordinary ipv4 header.
{
NdisGetNextBuffer(working_buffer, &working_buffer);
if (working_buffer == NULL)
{
Status = NDIS_STATUS_NOT_ACCEPTED;
goto failout;
}
NdisQueryBuffer(working_buffer, &working_block, &working_block_len);
udp_header = (PUDP_HEADER)working_block;
}
else
udp_header = (PUDP_HEADER)( (UCHAR*)working_block + sizeof(IP_HEADER));
}

if (ip_header->ip_foff)
pmstatus = PGPnetPMNeedTransformLight(PGPnetDriver.PolicyManagerHandle,
ip_header->ip_dest,
FALSE,
pAdapt);
else
pmstatus = PGPnetPMNeedTransform(PGPnetDriver.PolicyManagerHandle,
ip_header->ip_dest,
(PGPUInt16)(udp_header ? udp_header->dest_port : 0),
FALSE,
0,
0,
eth_header->eth_dstAddress,
pAdapt);

if ( kPGPNetPMPacketSent == pmstatus)
goto dropout;
if ( kPGPNetPMPacketWaiting == pmstatus)
goto dropout;
if ( kPGPNetPMPacketDrop == pmstatus)
goto dropout;
if ( kPGPNetPMPacketClear == pmstatus)
goto bailout;
if ( kPGPNetPMPacketEncrypt != pmstatus)
{
Status = NDIS_STATUS_FAILURE;
goto failout;
}

DBGPRINT(("We send a packet need to encrypt.../n"));

pgpPacket = PGPNdisPacketAllocWithXformPacket(&Status, pAdapt);

if (Status != NDIS_STATUS_SUCCESS)
goto failout;

pgpPacket->Binding = binding;
pgpPacket->srcPacket = Packet;

pgpPacket->NeedsEthernetTransform = FALSE;

PGPCopyPacketToBlock(pgpPacket->srcPacket, pgpPacket->srcBlock, &pgpPacket->srcBlockLen);

pgpPacket->ipAddress = ntohl(ip_header->ip_dest);

pgpPacket->port = udp_header ? udp_header->dest_port : 0;

pgpPacket->offset = ntohs(ip_header->ip_foff & IP_OFFSET) << 3;
if (pgpPacket->offset == 0)
pgpPacket->firstSrcBlock = TRUE;
// Check to see if it's in the outgoing fragment list.
packetHead = PacketHeadListQuery(pAdapt,
&pAdapt->outgoing_packet_head_list,
ip_header->ip_id,
pgpPacket->ipAddress);
// If there is no outgoing fragment list. Create one.
if (packetHead == NULL)
{
packetHead = PGPNdisPacketHeadAlloc(&Status, pAdapt);
newHead = TRUE;
}

if (Status != NDIS_STATUS_SUCCESS)
goto failout;

// Add timestamp, update head information.
if (packetHead->id == 0)
{
// Initialize packetHead
packetHead->ipAddress = pgpPacket->ipAddress;
packetHead->id = ip_header->ip_id;
packetHead->timeStamp = PgpKernelGetSystemTime();
}

if (packetHead->numFragments ==0)
packetHead->accumulatedLength = htons(ip_header->ip_len);
else
packetHead->accumulatedLength += htons(ip_header->ip_len) - IP_HEADER_SIZE;
packetHead->numFragments++;

if (IP_LAST_FRAGMENT(ip_header->ip_foff))
{
ASSERT(packetHead->totalLength == 0);
pgpPacket->lastSrcBlock = TRUE;
packetHead->totalLength = htons(ip_header->ip_len) + pgpPacket->offset;
}

// Insert this pgpPacket to the packet list
InsertPGPNdisPacket(pAdapt, packetHead, pgpPacket);
// Check status, if finished fire up the send sequence.

if ((packetHead->totalLength) && (packetHead->totalLength == packetHead->accumulatedLength))
{
// Have them all, send them all.
PGPnetPMStatus pm_status;
PPGPNDIS_PACKET extraPacket;

// Put an extra buffer there.
extraPacket = PGPNdisPacketAllocWithXformPacket(&Status, pAdapt);

AppendPGPNdisPacket(pAdapt, packetHead, extraPacket);

if ( !(packetHead->link)->lastSrcBlock )
{
// More fragment. Adjust packet length.
PIP_HEADER first_ip_hdr;
PUCHAR first_srcBlock;

first_srcBlock = (packetHead->link)->srcBlock;
first_ip_hdr = (PIP_HEADER)(first_srcBlock + ETHER_HEADER_SIZE);

// It is no longer a fragment
first_ip_hdr->ip_foff = ~(IP_MF) & first_ip_hdr->ip_foff;
first_ip_hdr->ip_len = htons(packetHead->totalLength);

first_ip_hdr->ip_chksum = 0;
first_ip_hdr->ip_chksum = iphdr_cksum((USHORT*)first_ip_hdr);
}

pm_status = PGPnetPMDoTransform(PGPnetDriver.PolicyManagerHandle,
packetHead->link,
FALSE,
pAdapt);

if (pm_status != kPGPNetPMPacketSent)
{
DBGPRINT(("!!!!! Yellow Alert! PGPnetPMDoTransform Error!/n"));
//PGPNdisPacketFree(pAdapt, pgpPacket);
PGPNdisPacketHeadFreeList(pAdapt, packetHead, TRUE);
PacketHeadListRemove(pAdapt, &pAdapt->outgoing_packet_head_list, packetHead);
PGPNdisPacketHeadFree(pAdapt, packetHead);

goto dropout;
}

if (packetHead->link->NeedsEthernetTransform)
PGPNetDoEthernetTransform(packetHead);

Status = MacSendPackets(pAdapt, packetHead);

assembleComplete = TRUE;

}
else
{
// Not finished, add to the outgoing list
if (newHead)
PacketHeadEnqueue(pAdapt, &pAdapt->outgoing_packet_head_list, packetHead);
}

goto dropout;
// Either way, return successful.
return Status;

/*
#ifdef NDIS51
//
// Use NDIS 5.1 packet stacking:
//
{
PNDIS_PACKET_STACK pStack;
BOOLEAN Remaining;

//
// Packet stacks: Check if we can use the same packet for sending down.
//

pStack = NdisIMGetCurrentPacketStack(Packet, &Remaining);
if (Remaining)
{
//
// We can reuse "Packet".
//
// NOTE: if we needed to keep per-packet information in packets
// sent down, we can use pStack->IMReserved[].
//
ASSERT(pStack);
//
// If the below miniport is going to low power state, stop sending down any packet.
//
NdisAcquireSpinLock(&pAdapt->general_lock);
if (pAdapt->PTDeviceState > NdisDeviceStateD0)
{
NdisReleaseSpinLock(&pAdapt->general_lock);
return NDIS_STATUS_FAILURE;
}
pAdapt->OutstandingSends++;
NdisReleaseSpinLock(&pAdapt->general_lock);
NdisSend(&Status,
pAdapt->BindingHandle,
Packet);

if (Status != NDIS_STATUS_PENDING)
{
ADAPT_DECR_PENDING_SENDS(pAdapt);
}

return(Status);
}
}
#endif // NDIS51

//
// We are either not using packet stacks, or there isn't stack space
// in the original packet passed down to us. Allocate a new packet
// to wrap the data with.
//
//
// If the below miniport is going to low power state, stop sending down any packet.
//

NdisAllocatePacket(&Status,
&MyPacket,
pAdapt->SendPacketPoolHandle);

if (Status == NDIS_STATUS_SUCCESS)
{
PSEND_RSVD SendRsvd;

//
// Save a pointer to the original packet in our reserved
// area in the new packet. This is needed so that we can
// get back to the original packet when the new packet's send
// is completed.
//
SendRsvd = (PSEND_RSVD)(MyPacket->ProtocolReserved);
SendRsvd->OriginalPkt = Packet;

MyPacket->Private.Flags = Flags;

//
// Set up the new packet so that it describes the same
// data as the original packet.
//
MyPacket->Private.Head = Packet->Private.Head;
MyPacket->Private.Tail = Packet->Private.Tail;
#ifdef WIN9X
//
// Work around the fact that NDIS does not initialize this
// to FALSE on Win9x.
//
MyPacket->Private.ValidCounts = FALSE;
#endif

//
// Copy the OOB Offset from the original packet to the new
// packet.
//
NdisMoveMemory(NDIS_OOB_DATA_FROM_PACKET(MyPacket),
NDIS_OOB_DATA_FROM_PACKET(Packet),
sizeof(NDIS_PACKET_OOB_DATA));

#ifndef WIN9X
//
// Copy the right parts of per packet info into the new packet.
// This API is not available on Win9x since task offload is
// not supported on that platform.
//
NdisIMCopySendPerPacketInfo(MyPacket, Packet);
#endif

//
// Copy the Media specific information
//
NDIS_GET_PACKET_MEDIA_SPECIFIC_INFO(Packet,
&MediaSpecificInfo,
&MediaSpecificInfoSize);

if (MediaSpecificInfo || MediaSpecificInfoSize)
{
NDIS_SET_PACKET_MEDIA_SPECIFIC_INFO(MyPacket,
MediaSpecificInfo,
MediaSpecificInfoSize);
}

NdisSend(&Status,
pAdapt->BindingHandle,
MyPacket);


if (Status != NDIS_STATUS_PENDING)
{
#ifndef WIN9X
NdisIMCopySendCompletePerPacketInfo (Packet, MyPacket);
#endif
NdisFreePacket(MyPacket);
ADAPT_DECR_PENDING_SENDS(pAdapt);
}
}
else
{
ADAPT_DECR_PENDING_SENDS(pAdapt);
//
// We are out of packets. Silently drop it. Alternatively we can deal with it:
// - By keeping separate send and receive pools
// - Dynamically allocate more pools as needed and free them when not needed
//
}

return(Status);
*/

bailout:

pgpPacket = PGPNdisPacketAllocWithBindingContext(&Status, pAdapt);

if (Status != NDIS_STATUS_SUCCESS)
goto failout;

NdisAllocatePacket(&Status,
&MyPacket,
pAdapt->SendPacketPoolHandle);

if (Status == NDIS_STATUS_SUCCESS)
{
PSEND_RSVD SendRsvd;

SendRsvd = (PSEND_RSVD)(MyPacket->ProtocolReserved);
SendRsvd->OriginalPkt = Packet;

MyPacket->Private.Flags = Flags;

MyPacket->Private.Head = Packet->Private.Head;
MyPacket->Private.Tail = Packet->Private.Tail;
#ifdef WIN9X
MyPacket->Private.ValidCounts = FALSE;
#endif
/*
NdisMoveMemory(NDIS_OOB_DATA_FROM_PACKET(MyPacket),
NDIS_OOB_DATA_FROM_PACKET(Packet),
sizeof(NDIS_PACKET_OOB_DATA));
*/

#ifndef WIN9X
NdisIMCopySendPerPacketInfo(MyPacket, Packet);
#endif

NDIS_GET_PACKET_MEDIA_SPECIFIC_INFO(Packet,
&MediaSpecificInfo,
&MediaSpecificInfoSize);

if (MediaSpecificInfo || MediaSpecificInfoSize)
{
NDIS_SET_PACKET_MEDIA_SPECIFIC_INFO(MyPacket,
MediaSpecificInfo,
MediaSpecificInfoSize);
}

pgpPacket->srcPacket = MyPacket;
pgpPacket->Binding = binding;

PacketEnqueue(pAdapt, &pAdapt->sent_plainpacket_list, pgpPacket);

NdisSend(&Status,
pAdapt->BindingHandle,
MyPacket);


if (Status != NDIS_STATUS_PENDING)
{
/*
#ifndef WIN9X
NdisIMCopySendCompletePerPacketInfo (Packet, MyPacket);
#endif
*/
NdisFreePacket(Packet);

pgpPacket = PacketRemoveBySrcPacket(pAdapt, &pAdapt->sent_plainpacket_list, MyPacket);
PGPNdisPacketFreeWithBindingContext(pAdapt, pgpPacket);

ADAPT_DECR_PENDING_SENDS(pAdapt);
}
}
/*
NdisSend(&Status,
pAdapt->BindingHandle,
Packet);

if (Status != NDIS_STATUS_PENDING)
{
pgpPacket = PacketRemoveBySrcPacket(pAdapt, &pAdapt->sent_plainpacket_list, Packet);
PGPNdisPacketFreeWithBindingContext(pAdapt, pgpPacket);
//add
ADAPT_DECR_PENDING_SENDS(pAdapt);
//end
}
*/
pAdapt->SendPackets++;

failout:

return Status;

dropout:
if (assembleComplete == FALSE)
Status = NDIS_STATUS_SUCCESS;

return Status;
}


VOID
MPSendPackets(
IN NDIS_HANDLE MiniportAdapterContext,
IN PPNDIS_PACKET PacketArray,
IN UINT NumberOfPackets
)
/*++

Routine Description:

Send Packet Array handler. Either this or our SendPacket handler is called
based on which one is enabled in our Miniport Characteristics.

Arguments:

MiniportAdapterContext Pointer to our adapter
PacketArray Set of packets to send
NumberOfPackets Self-explanatory

Return Value:

None

--*/
{
PADAPT pAdapt = (PADAPT)MiniportAdapterContext;
NDIS_STATUS Status;
UINT i;
PVOID MediaSpecificInfo = NULL;
UINT MediaSpecificInfoSize = 0;

//add
DBGPRINT(("MPSendPackets function has been called.../n"));
//end

for (i = 0; i < NumberOfPackets; i++)
{
PNDIS_PACKET Packet, MyPacket;

Packet = PacketArray[i];
//
// The driver should fail the send if the virtual miniport is in low
// power state
//
if (pAdapt->MPDeviceState > NdisDeviceStateD0)
{
NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt),
Packet,
NDIS_STATUS_FAILURE);
continue;
}

#ifdef NDIS51

//
// Use NDIS 5.1 packet stacking:
//
{
PNDIS_PACKET_STACK pStack;
BOOLEAN Remaining;

//
// Packet stacks: Check if we can use the same packet for sending down.
//
pStack = NdisIMGetCurrentPacketStack(Packet, &Remaining);
if (Remaining)
{
//
// We can reuse "Packet".
//
// NOTE: if we needed to keep per-packet information in packets
// sent down, we can use pStack->IMReserved[].
//
ASSERT(pStack);
//
// If the below miniport is going to low power state, stop sending down any packet.
//
NdisAcquireSpinLock(&pAdapt->general_lock);
if (pAdapt->PTDeviceState > NdisDeviceStateD0)
{
NdisReleaseSpinLock(&pAdapt->general_lock);
NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt),
Packet,
NDIS_STATUS_FAILURE);
}
else
{
pAdapt->OutstandingSends++;
NdisReleaseSpinLock(&pAdapt->general_lock);

NdisSend(&Status,
pAdapt->BindingHandle,
Packet);

if (Status != NDIS_STATUS_PENDING)
{
NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt),
Packet,
Status);

ADAPT_DECR_PENDING_SENDS(pAdapt);
}
}
continue;
}
}
#endif
do
{
NdisAcquireSpinLock(&pAdapt->general_lock);
//
// If the below miniport is going to low power state, stop sending down any packet.
//
if (pAdapt->PTDeviceState > NdisDeviceStateD0)
{
NdisReleaseSpinLock(&pAdapt->general_lock);
Status = NDIS_STATUS_FAILURE;
break;
}
pAdapt->OutstandingSends++;
NdisReleaseSpinLock(&pAdapt->general_lock);

NdisAllocatePacket(&Status,
&MyPacket,
pAdapt->SendPacketPoolHandle);

if (Status == NDIS_STATUS_SUCCESS)
{
PSEND_RSVD SendRsvd;

SendRsvd = (PSEND_RSVD)(MyPacket->ProtocolReserved);
SendRsvd->OriginalPkt = Packet;

MyPacket->Private.Flags = NdisGetPacketFlags(Packet);

MyPacket->Private.Head = Packet->Private.Head;
MyPacket->Private.Tail = Packet->Private.Tail;
#ifdef WIN9X
//
// Work around the fact that NDIS does not initialize this
// to FALSE on Win9x.
//
MyPacket->Private.ValidCounts = FALSE;
#endif // WIN9X

//
// Copy the OOB data from the original packet to the new
// packet.
//
NdisMoveMemory(NDIS_OOB_DATA_FROM_PACKET(MyPacket),
NDIS_OOB_DATA_FROM_PACKET(Packet),
sizeof(NDIS_PACKET_OOB_DATA));
//
// Copy relevant parts of the per packet info into the new packet
//
#ifndef WIN9X
NdisIMCopySendPerPacketInfo(MyPacket, Packet);
#endif

//
// Copy the Media specific information
//
NDIS_GET_PACKET_MEDIA_SPECIFIC_INFO(Packet,
&MediaSpecificInfo,
&MediaSpecificInfoSize);

if (MediaSpecificInfo || MediaSpecificInfoSize)
{
NDIS_SET_PACKET_MEDIA_SPECIFIC_INFO(MyPacket,
MediaSpecificInfo,
MediaSpecificInfoSize);
}

NdisSend(&Status,
pAdapt->BindingHandle,
MyPacket);

if (Status != NDIS_STATUS_PENDING)
{
#ifndef WIN9X
NdisIMCopySendCompletePerPacketInfo (Packet, MyPacket);
#endif
NdisFreePacket(MyPacket);
ADAPT_DECR_PENDING_SENDS(pAdapt);
}
}
else
{
//
// The driver cannot allocate a packet.
//
ADAPT_DECR_PENDING_SENDS(pAdapt);
}
}
while (FALSE);

if (Status != NDIS_STATUS_PENDING)
{
NdisMSendComplete(ADAPT_MINIPORT_HANDLE(pAdapt),
Packet,
Status);
}
}
}


NDIS_STATUS
MPQueryInformation(
IN NDIS_HANDLE MiniportAdapterContext,
IN NDIS_OID Oid,
IN PVOID InformationBuffer,
IN ULONG InformationBufferLength,
OUT PULONG BytesWritten,
OUT PULONG BytesNeeded
)
/*++

Routine Description:

Entry point called by NDIS to query for the value of the specified OID.
Typical processing is to forward the query down to the underlying miniport.

The following OIDs are filtered here:

OID_PNP_QUERY_POWER - return success right here

OID_GEN_SUPPORTED_GUIDS - do not forward, otherwise we will show up
multiple instances of private GUIDs supported by the underlying miniport.

OID_PNP_CAPABILITIES - we do send this down to the lower miniport, but
the values returned are postprocessed before we complete this request;
see PtRequestComplete.

NOTE on OID_TCP_TASK_OFFLOAD - if this IM driver modifies the contents
of data it passes through such that a lower miniport may not be able
to perform TCP task offload, then it should not forward this OID down,
but fail it here with the status NDIS_STATUS_NOT_SUPPORTED. This is to
avoid performing incorrect transformations on data.

If our miniport edge (upper edge) is at a low-power state, fail the request.

If our protocol edge (lower edge) has been notified of a low-power state,
we pend this request until the miniport below has been set to D0. Since
requests to miniports are serialized always, at most a single request will
be pended.

Arguments:

MiniportAdapterContext Pointer to the adapter structure
Oid Oid for this query
InformationBuffer Buffer for information
InformationBufferLength Size of this buffer
BytesWritten Specifies how much info is written
BytesNeeded In case the buffer is smaller than what we need, tell them how much is needed


Return Value:

Return code from the NdisRequest below.

--*/
{
PADAPT pAdapt = (PADAPT)MiniportAdapterContext;
NDIS_STATUS Status = NDIS_STATUS_FAILURE;

do
{
if (Oid == OID_PNP_QUERY_POWER)
{
//
// Do not forward this.
//
Status = NDIS_STATUS_SUCCESS;
break;
}

if (Oid == OID_GEN_SUPPORTED_GUIDS)
{
//
// Do not forward this, otherwise we will end up with multiple
// instances of private GUIDs that the underlying miniport
// supports.
//
Status = NDIS_STATUS_NOT_SUPPORTED;
break;
}

if (Oid == OID_TCP_TASK_OFFLOAD)
{
//
// Fail this -if- this driver performs data transformations
// that can interfere with a lower driver's ability to offload
// TCP tasks.
//
// Status = NDIS_STATUS_NOT_SUPPORTED;
// break;
//
}
//
// If the miniport below is unbinding, just fail any request
//
NdisAcquireSpinLock(&pAdapt->general_lock);
if (pAdapt->UnbindingInProcess == TRUE)
{
NdisReleaseSpinLock(&pAdapt->general_lock);
Status = NDIS_STATUS_FAILURE;
break;
}
NdisReleaseSpinLock(&pAdapt->general_lock);
//
// All other queries are failed, if the miniport is not at D0,
//
if (pAdapt->MPDeviceState > NdisDeviceStateD0)
{
Status = NDIS_STATUS_FAILURE;
break;
}

pAdapt->Request.RequestType = NdisRequestQueryInformation;
pAdapt->Request.DATA.QUERY_INFORMATION.Oid = Oid;
pAdapt->Request.DATA.QUERY_INFORMATION.InformationBuffer = InformationBuffer;
pAdapt->Request.DATA.QUERY_INFORMATION.InformationBufferLength = InformationBufferLength;
pAdapt->BytesNeeded = BytesNeeded;
pAdapt->BytesReadOrWritten = BytesWritten;

//
// If the miniport below is binding, fail the request
//
NdisAcquireSpinLock(&pAdapt->general_lock);

if (pAdapt->UnbindingInProcess == TRUE)
{
NdisReleaseSpinLock(&pAdapt->general_lock);
Status = NDIS_STATUS_FAILURE;
break;
}
//
// If the Protocol device state is OFF, mark this request as being
// pended. We queue this until the device state is back to D0.
//
if ((pAdapt->PTDeviceState > NdisDeviceStateD0)
&& (pAdapt->StandingBy == FALSE))
{
pAdapt->QueuedRequest = TRUE;
NdisReleaseSpinLock(&pAdapt->general_lock);
Status = NDIS_STATUS_PENDING;
break;
}
//
// This is in the process of powering down the system, always fail the request
//
if (pAdapt->StandingBy == TRUE)
{
NdisReleaseSpinLock(&pAdapt->general_lock);
Status = NDIS_STATUS_FAILURE;
break;
}
pAdapt->OutstandingRequests = TRUE;

NdisReleaseSpinLock(&pAdapt->general_lock);

//
// default case, most requests will be passed to the miniport below
//
NdisRequest(&Status,
pAdapt->BindingHandle,
&pAdapt->Request);


if (Status != NDIS_STATUS_PENDING)
{
PtRequestComplete(pAdapt, &pAdapt->Request, Status);
Status = NDIS_STATUS_PENDING;
}

} while (FALSE);

return(Status);

}


VOID
MPQueryPNPCapabilities(
IN OUT PADAPT pAdapt,
OUT PNDIS_STATUS pStatus
)
/*++

Routine Description:

Postprocess a request for OID_PNP_CAPABILITIES that was forwarded
down to the underlying miniport, and has been completed by it.

Arguments:

pAdapt - Pointer to the adapter structure
pStatus - Place to return final status

Return Value:

None.

--*/

{
PNDIS_PNP_CAPABILITIES pPNPCapabilities;
PNDIS_PM_WAKE_UP_CAPABILITIES pPMstruct;

if (pAdapt->Request.DATA.QUERY_INFORMATION.InformationBufferLength >= sizeof(NDIS_PNP_CAPABILITIES))
{
pPNPCapabilities = (PNDIS_PNP_CAPABILITIES)(pAdapt->Request.DATA.QUERY_INFORMATION.InformationBuffer);

//
// The following fields must be overwritten by an IM driver.
//
pPMstruct= & pPNPCapabilities->WakeUpCapabilities;
pPMstruct->MinMagicPacketWakeUp = NdisDeviceStateUnspecified;
pPMstruct->MinPatternWakeUp = NdisDeviceStateUnspecified;
pPMstruct->MinLinkChangeWakeUp = NdisDeviceStateUnspecified;
*pAdapt->BytesReadOrWritten = sizeof(NDIS_PNP_CAPABILITIES);
*pAdapt->BytesNeeded = 0;


//
// Setting our internal flags
// Default, device is ON
//
pAdapt->MPDeviceState = NdisDeviceStateD0;
pAdapt->PTDeviceState = NdisDeviceStateD0;

*pStatus = NDIS_STATUS_SUCCESS;
}
else
{
*pAdapt->BytesNeeded= sizeof(NDIS_PNP_CAPABILITIES);
*pStatus = NDIS_STATUS_RESOURCES;
}
}


NDIS_STATUS
MPSetInformation(
IN NDIS_HANDLE MiniportAdapterContext,
IN NDIS_OID Oid,
IN PVOID InformationBuffer,
IN ULONG InformationBufferLength,
OUT PULONG BytesRead,
OUT PULONG BytesNeeded
)
/*++

Routine Description:

Miniport SetInfo handler.

In the case of OID_PNP_SET_POWER, record the power state and return the OID.
Do not pass below
If the device is suspended, do not block the SET_POWER_OID
as it is used to reactivate the Passthru miniport


PM- If the MP is not ON (DeviceState > D0) return immediately (except for 'query power' and 'set power')
If MP is ON, but the PT is not at D0, then queue the queue the request for later processing

Requests to miniports are always serialized


Arguments:

MiniportAdapterContext Pointer to the adapter structure
Oid Oid for this query
InformationBuffer Buffer for information
InformationBufferLength Size of this buffer
BytesRead Specifies how much info is read
BytesNeeded In case the buffer is smaller than what we need, tell them how much is needed

Return Value:

Return code from the NdisRequest below.

--*/
{
PADAPT pAdapt = (PADAPT)MiniportAdapterContext;
NDIS_STATUS Status;

Status = NDIS_STATUS_FAILURE;

do
{
//
// The Set Power should not be sent to the miniport below the Passthru, but is handled internally
//
if (Oid == OID_PNP_SET_POWER)
{
MPProcessSetPowerOid(&Status,
pAdapt,
InformationBuffer,
InformationBufferLength,
BytesRead,
BytesNeeded);
break;

}

//
// If the miniport below is unbinding, fail the request
//
NdisAcquireSpinLock(&pAdapt->general_lock);
if (pAdapt->UnbindingInProcess == TRUE)
{
NdisReleaseSpinLock(&pAdapt->general_lock);
Status = NDIS_STATUS_FAILURE;
break;
}
NdisReleaseSpinLock(&pAdapt->general_lock);
//
// All other Set Information requests are failed, if the miniport is
// not at D0 or is transitioning to a device state greater than D0.
//
if (pAdapt->MPDeviceState > NdisDeviceStateD0)
{
Status = NDIS_STATUS_FAILURE;
break;
}

// Set up the Request and return the result
pAdapt->Request.RequestType = NdisRequestSetInformation;
pAdapt->Request.DATA.SET_INFORMATION.Oid = Oid;
pAdapt->Request.DATA.SET_INFORMATION.InformationBuffer = InformationBuffer;
pAdapt->Request.DATA.SET_INFORMATION.InformationBufferLength = InformationBufferLength;
pAdapt->BytesNeeded = BytesNeeded;
pAdapt->BytesReadOrWritten = BytesRead;

//
// If the miniport below is unbinding, fail the request
//
NdisAcquireSpinLock(&pAdapt->general_lock);
if (pAdapt->UnbindingInProcess == TRUE)
{
NdisReleaseSpinLock(&pAdapt->general_lock);
Status = NDIS_STATUS_FAILURE;
break;
}

//
// If the device below is at a low power state, we cannot send it the
// request now, and must pend it.
//
if ((pAdapt->PTDeviceState > NdisDeviceStateD0)
&& (pAdapt->StandingBy == FALSE))
{
pAdapt->QueuedRequest = TRUE;
NdisReleaseSpinLock(&pAdapt->general_lock);
Status = NDIS_STATUS_PENDING;
break;
}
//
// This is in the process of powering down the system, always fail the request
//
if (pAdapt->StandingBy == TRUE)
{
NdisReleaseSpinLock(&pAdapt->general_lock);
Status = NDIS_STATUS_FAILURE;
break;
}
pAdapt->OutstandingRequests = TRUE;

NdisReleaseSpinLock(&pAdapt->general_lock);
//
// Forward the request to the device below.
//
NdisRequest(&Status,
pAdapt->BindingHandle,
&pAdapt->Request);

if (Status != NDIS_STATUS_PENDING)
{
*BytesRead = pAdapt->Request.DATA.SET_INFORMATION.BytesRead;
*BytesNeeded = pAdapt->Request.DATA.SET_INFORMATION.BytesNeeded;
pAdapt->OutstandingRequests = FALSE;
}

} while (FALSE);

return(Status);
}


VOID
MPProcessSetPowerOid(
IN OUT PNDIS_STATUS pNdisStatus,
IN PADAPT pAdapt,
IN PVOID InformationBuffer,
IN ULONG InformationBufferLength,
OUT PULONG BytesRead,
OUT PULONG BytesNeeded
)
/*++

Routine Description:
This routine does all the procssing for a request with a SetPower Oid
The miniport shoud accept the Set Power and transition to the new state

The Set Power should not be passed to the miniport below

If the IM miniport is going into a low power state, then there is no guarantee if it will ever
be asked go back to D0, before getting halted. No requests should be pended or queued.


Arguments:
pNdisStatus - Status of the operation
pAdapt - The Adapter structure
InformationBuffer - The New DeviceState
InformationBufferLength
BytesRead - No of bytes read
BytesNeeded - No of bytes needed


Return Value:
Status - NDIS_STATUS_SUCCESS if all the wait events succeed.

--*/
{


NDIS_DEVICE_POWER_STATE NewDeviceState;

DBGPRINT(("==>MPProcessSetPowerOid: Adapt %p/n", pAdapt));

ASSERT (InformationBuffer != NULL);

*pNdisStatus = NDIS_STATUS_FAILURE;

do
{
//
// Check for invalid length
//
if (InformationBufferLength < sizeof(NDIS_DEVICE_POWER_STATE))
{
*pNdisStatus = NDIS_STATUS_INVALID_LENGTH;
break;
}

NewDeviceState = (*(PNDIS_DEVICE_POWER_STATE)InformationBuffer);

//
// Check for invalid device state
//
if ((pAdapt->MPDeviceState > NdisDeviceStateD0) && (NewDeviceState != NdisDeviceStateD0))
{
//
// If the miniport is in a non-D0 state, the miniport can only receive a Set Power to D0
//
ASSERT (!(pAdapt->MPDeviceState > NdisDeviceStateD0) && (NewDeviceState != NdisDeviceStateD0));

*pNdisStatus = NDIS_STATUS_FAILURE;
break;
}

//
// Is the miniport transitioning from an On (D0) state to an Low Power State (>D0)
// If so, then set the StandingBy Flag - (Block all incoming requests)
//
if (pAdapt->MPDeviceState == NdisDeviceStateD0 && NewDeviceState > NdisDeviceStateD0)
{
pAdapt->StandingBy = TRUE;
}

//
// If the miniport is transitioning from a low power state to ON (D0), then clear the StandingBy flag
// All incoming requests will be pended until the physical miniport turns ON.
//
if (pAdapt->MPDeviceState > NdisDeviceStateD0 && NewDeviceState == NdisDeviceStateD0)
{
pAdapt->StandingBy = FALSE;
}

//
// Now update the state in the pAdapt structure;
//
pAdapt->MPDeviceState = NewDeviceState;

*pNdisStatus = NDIS_STATUS_SUCCESS;


} while (FALSE);

if (*pNdisStatus == NDIS_STATUS_SUCCESS)
{
//
// The miniport resume from low power state
//
if (pAdapt->StandingBy == FALSE)
{
//
// If we need to indicate the media connect state
//
if (pAdapt->LastIndicatedStatus != pAdapt->LatestUnIndicateStatus)
{
NdisMIndicateStatus(pAdapt->MiniportHandle,
pAdapt->LatestUnIndicateStatus,
(PVOID)NULL,
0);
NdisMIndicateStatusComplete(pAdapt->MiniportHandle);
pAdapt->LastIndicatedStatus = pAdapt->LatestUnIndicateStatus;
}
}
else
{
//
// Initialize LatestUnIndicatedStatus
//
pAdapt->LatestUnIndicateStatus = pAdapt->LastIndicatedStatus;
}
*BytesRead = sizeof(NDIS_DEVICE_POWER_STATE);
*BytesNeeded = 0;
}
else
{
*BytesRead = 0;
*BytesNeeded = sizeof (NDIS_DEVICE_POWER_STATE);
}

DBGPRINT(("<==MPProcessSetPowerOid: Adapt %p/n", pAdapt));
}


VOID
MPReturnPacket(
IN NDIS_HANDLE MiniportAdapterContext,
IN PNDIS_PACKET Packet
)
/*++

Routine Description:

NDIS Miniport entry point called whenever protocols are done with
a packet that we had indicated up and they had queued up for returning
later.

Arguments:

MiniportAdapterContext - pointer to ADAPT structure
Packet - packet being returned.

Return Value:

None.

--*/
{
PADAPT pAdapt = (PADAPT)MiniportAdapterContext;

//add
DBGPRINT(("MPReturnPacket function has been called.../n"));
//end

#ifdef NDIS51
//
// Packet stacking: Check if this packet belongs to us.
//
if (NdisGetPoolFromPacket(Packet) != pAdapt->RecvPacketPoolHandle)
{
//
// We reused the original packet in a receive indication.
// Simply return it to the miniport below us.
//
NdisReturnPackets(&Packet, 1);
}
else
#endif // NDIS51
{
//
// This is a packet allocated from this IM's receive packet pool.
// Reclaim our packet, and return the original to the driver below.
//

PNDIS_PACKET MyPacket;
PRECV_RSVD RecvRsvd;

RecvRsvd = (PRECV_RSVD)(Packet->MiniportReserved);
MyPacket = RecvRsvd->OriginalPkt;

NdisFreePacket(Packet);
NdisReturnPackets(&MyPacket, 1);
}
}


NDIS_STATUS
MPTransferData(
OUT PNDIS_PACKET Packet,
OUT PUINT BytesTransferred,
IN NDIS_HANDLE MiniportAdapterContext,
IN NDIS_HANDLE MiniportReceiveContext,
IN UINT ByteOffset,
IN UINT BytesToTransfer
)
/*++

Routine Description:

Miniport's transfer data handler.

Arguments:

Packet Destination packet
BytesTransferred Place-holder for how much data was copied
MiniportAdapterContext Pointer to the adapter structure
MiniportReceiveContext Context
ByteOffset Offset into the packet for copying data
BytesToTransfer How much to copy.

Return Value:

Status of transfer

--*/
{
PADAPT pAdapt = (PADAPT)MiniportAdapterContext;
NDIS_STATUS Status;
//add
PBINDING_CONTEXT binding = NULL;
PPGPNDIS_PACKET pgpPacket;
BOOLEAN fragment = TRUE;
//end
//add
DBGPRINT(("MPTransferData function has been called.../n"));
//end

//
// Return, if the device is OFF
//

if (IsIMDeviceStateOn(pAdapt) == FALSE)
{
return NDIS_STATUS_FAILURE;
}
//add
pgpPacket = PacketRemoveBySrcPacket(pAdapt, &pAdapt->incoming_indicateComplete_wait_list, MiniportReceiveContext);

if (pgpPacket == NULL)
{
pgpPacket = PacketRemoveBySrcPacket(pAdapt, &pAdapt->incoming_fragment_indicateComplete_wait_list, MiniportReceiveContext);
}
else
{
fragment = FALSE;
}

if (pgpPacket == NULL)
{
pgpPacket = PGPNdisPacketAllocWithBindingContext(&Status, pAdapt);

pgpPacket->srcPacket = Packet;
pgpPacket->Binding = binding;

PacketEnqueue(pAdapt, &pAdapt->incoming_plaintransferComplete_wait_list, pgpPacket);

NdisTransferData(&Status,
pAdapt->BindingHandle,
MiniportReceiveContext,
ByteOffset,
BytesToTransfer,
Packet,
BytesTransferred);

if (Status != NDIS_STATUS_PENDING)
{
pgpPacket = PacketRemoveBySrcPacket(pAdapt, &pAdapt->incoming_plaintransferComplete_wait_list, Packet);
PGPNdisPacketFreeWithBindingContext(pAdapt, pgpPacket);
}
}
else
{
ASSERT(FALSE);
}

return NDIS_STATUS_SUCCESS;

//end
/*
NdisTransferData(&Status,
pAdapt->BindingHandle,
MiniportReceiveContext,
ByteOffset,
BytesToTransfer,
Packet,
BytesTransferred);

return(Status);
*/
}

VOID
MPHalt(
IN NDIS_HANDLE MiniportAdapterContext
)
/*++

Routine Description:

Halt handler. All the hard-work for clean-up is done here.

Arguments:

MiniportAdapterContext Pointer to the Adapter

Return Value:

None.

--*/
{
PADAPT pAdapt = (PADAPT)MiniportAdapterContext;
NDIS_STATUS Status;
PADAPT *ppCursor;

DBGPRINT(("==>MiniportHalt: Adapt %p/n", pAdapt));

//
// Remove this adapter from the global list
//
NdisAcquireSpinLock(&GlobalLock);

for (ppCursor = &pAdaptList; *ppCursor != NULL; ppCursor = &(*ppCursor)->Next)
{
if (*ppCursor == pAdapt)
{
*ppCursor = pAdapt->Next;
break;
}
}

NdisReleaseSpinLock(&GlobalLock);

// BEGIN_PTUSERIO
//
// Make Suprise Unbind Notification
//
DevOnUnbindAdapter( pAdapt->pOpenContext );
// END_PTUSERIO

//
// Delete the ioctl interface that was created when the miniport
// was created.
//
(VOID)PtDeregisterDevice();

if (pAdapt->BindingHandle != NULL)
{
NDIS_STATUS LocalStatus;

//
// Close the binding to the adapter
//

NdisResetEvent(&pAdapt->Event);

NdisCloseAdapter(&LocalStatus, pAdapt->BindingHandle);
pAdapt->BindingHandle = NULL;

if (LocalStatus == NDIS_STATUS_PENDING)
{
NdisWaitEvent(&pAdapt->Event, 0);
LocalStatus = pAdapt->Status;
}

ASSERT (LocalStatus == NDIS_STATUS_SUCCESS);
}

// BEGIN_PTUSERIO
//
// Remove Reference To The Adapter
//
PtDerefAdapter( pAdapt );
// END_PTUSERIO

DBGPRINT(("<== MiniportHalt: pAdapt %p/n", pAdapt));
}


#ifdef NDIS51_MINIPORT

VOID
MPCancelSendPackets(
IN NDIS_HANDLE MiniportAdapterContext,
IN PVOID CancelId
)
/*++

Routine Description:

The miniport entry point to handle cancellation of all send packets
that match the given CancelId. If we have queued any packets that match
this, then we should dequeue them and call NdisMSendComplete for all
such packets, with a status of NDIS_STATUS_REQUEST_ABORTED.

We should also call NdisCancelSendPackets in turn, on each lower binding
that this adapter corresponds to. This is to let miniports below cancel
any matching packets.

Arguments:

MiniportAdapterContext - pointer to ADAPT structure
CancelId - ID of packets to be cancelled.

Return Value:

None

--*/
{
PADAPT pAdapt = (PADAPT)MiniportAdapterContext;

//
// If we queue packets on our adapter structure, this would be
// the place to acquire a spinlock to it, unlink any packets whose
// Id matches CancelId, release the spinlock and call NdisMSendComplete
// with NDIS_STATUS_REQUEST_ABORTED for all unlinked packets.
//

//
// Next, pass this down so that we let the miniport(s) below cancel
// any packets that they might have queued.
//
NdisCancelSendPackets(pAdapt->BindingHandle, CancelId);

return;
}

VOID
MPDevicePnPEvent(
IN NDIS_HANDLE MiniportAdapterContext,
IN NDIS_DEVICE_PNP_EVENT DevicePnPEvent,
IN PVOID InformationBuffer,
IN ULONG InformationBufferLength
)
/*++

Routine Description:

This handler is called to notify us of PnP events directed to
our miniport device object.

Arguments:

MiniportAdapterContext - pointer to ADAPT structure
DevicePnPEvent - the event
InformationBuffer - Points to additional event-specific information
InformationBufferLength - length of above

Return Value:

None
--*/
{
// TBD - add code/comments about processing this.

UNREFERENCED_PARAMETER(MiniportAdapterContext);
UNREFERENCED_PARAMETER(DevicePnPEvent);
UNREFERENCED_PARAMETER(InformationBuffer);
UNREFERENCED_PARAMETER(InformationBufferLength);

return;
}

VOID
MPAdapterShutdown(
IN NDIS_HANDLE MiniportAdapterContext
)
/*++

Routine Description:

This handler is called to notify us of an impending system shutdown.

Arguments:

MiniportAdapterContext - pointer to ADAPT structure

Return Value:

None
--*/
{
UNREFERENCED_PARAMETER(MiniportAdapterContext);

return;
}

#endif


// BEGIN_PTUSERIO

//
// Removed MPFreeAllPacketPools. Functionality incorporated in PtDerefAdapter.
//

// END_PTUSERIO

PVPN_ADAPTER AllocateVpnAdapter()
{
NDIS_STATUS status;

PADAPT VpnAdapter;

if (VpnAdapterCreated)
{
VpnAdapter = NULL;
//DBG_LEAVE(0);
return (VpnAdapter);
}
/*
status = NdisAllocateMemory(&VpnAdapter,
sizeof(VPN_ADAPTER),
0,
HighestAcceptableAddress
);
*/
status = NdisAllocateMemoryWithTag(&VpnAdapter, sizeof(ADAPT), TAG);

if (status != NDIS_STATUS_SUCCESS)
{
//DBG_PRINT(("!!!!! NdisAllocateMemory failed status=%Xh/n", status););
VpnAdapter = NULL;
//DBG_LEAVE(0);
return (VpnAdapter);
}

NdisZeroMemory(VpnAdapter, sizeof(ADAPT));

VpnAdapter->MacContext = VpnAdapter;
VpnAdapter->BindingHandle = NULL;//NdisBindingHandleToRealMac

VpnAdapterCreated = TRUE;
// VpnAdapterGlobal = VpnAdapter;

// Any of the supported types.
VpnAdapter->NumSupportedMediums = MediumArraySize;
VpnAdapter->SupportedMediums = &MediumArray[0];
VpnAdapter->media = (UINT) -1;

NdisAllocateSpinLock(&VpnAdapter->general_lock);

return (VpnAdapter);
}

VOID FreeVpnAdapter(
IN PADAPT VpnAdapter
)
{
NdisFreeSpinLock(&VpnAdapter->general_lock);

pAdaptList = NULL;//VpnAdapterGlobal
VpnAdapterCreated = FALSE;

//PGPnetDriver.NdisMacHandle = NULL;

NdisFreeMemory((PVOID)VpnAdapter, sizeof(ADAPT), 0);
}

VOID PGPNetDoEthernetTransform(PPGPNDIS_PACKET_HEAD packetHead)
{
PPGPNDIS_PACKET packet;

packet = packetHead->link;

if (packet != NULL)
NdisMoveMemory(packet->srcBlock, packet->ethernetAddress, 6);
}

#if DBG_MESSAGE
static struct _SupportedOidArray {

PCHAR OidName;
NDIS_OID Oid;

} SupportedOidArray[ ] = {

"OID_GEN_SUPPORTED_LIST", 0x00010101,
"OID_GEN_HARDWARE_STATUS", 0x00010102,
"OID_GEN_MEDIA_SUPPORTED", 0x00010103,
"OID_GEN_MEDIA_IN_USE", 0x00010104,
"OID_GEN_MAXIMUM_LOOKAHEAD", 0x00010105,
"OID_GEN_MAXIMUM_FRAME_SIZE", 0x00010106,
"OID_GEN_LINK_SPEED", 0x00010107,
"OID_GEN_TRANSMIT_BUFFER_SPACE", 0x00010108,
"OID_GEN_RECEIVE_BUFFER_SPACE", 0x00010109,
"OID_GEN_TRANSMIT_BLOCK_SIZE", 0x0001010A,
"OID_GEN_RECEIVE_BLOCK_SIZE", 0x0001010B,
"OID_GEN_VENDOR_ID", 0x0001010C,
"OID_GEN_VENDOR_DESCRIPTION", 0x0001010D,
"OID_GEN_CURRENT_PACKET_FILTER", 0x0001010E,
"OID_GEN_CURRENT_LOOKAHEAD", 0x0001010F,
"OID_GEN_DRIVER_VERSION", 0x00010110,
"OID_GEN_MAXIMUM_TOTAL_SIZE", 0x00010111,
"OID_GEN_PROTOCOL_OPTIONS", 0x00010112,
"OID_GEN_MAC_OPTIONS", 0x00010113,
"OID_GEN_MEDIA_CONNECT_STATUS", 0x00010114,
"OID_GEN_XMIT_OK", 0x00020101,
"OID_GEN_RCV_OK", 0x00020102,
"OID_GEN_XMIT_ERROR", 0x00020103,
"OID_GEN_RCV_ERROR", 0x00020104,
"OID_GEN_RCV_NO_BUFFER", 0x00020105,
"OID_GEN_DIRECTED_BYTES_XMIT", 0x00020201,
"OID_GEN_DIRECTED_FRAMES_XMIT", 0x00020202,
"OID_GEN_MULTICAST_BYTES_XMIT", 0x00020203,
"OID_GEN_MULTICAST_FRAMES_XMIT", 0x00020204,
"OID_GEN_BROADCAST_BYTES_XMIT", 0x00020205,
"OID_GEN_BROADCAST_FRAMES_XMIT", 0x00020206,
"OID_GEN_DIRECTED_BYTES_RCV", 0x00020207,
"OID_GEN_DIRECTED_FRAMES_RCV", 0x00020208,
"OID_GEN_MULTICAST_BYTES_RCV", 0x00020209,
"OID_GEN_MULTICAST_FRAMES_RCV", 0x0002020A,
"OID_GEN_BROADCAST_BYTES_RCV", 0x0002020B,
"OID_GEN_BROADCAST_FRAMES_RCV", 0x0002020C,
"OID_GEN_RCV_CRC_ERROR", 0x0002020D,
"OID_GEN_TRANSMIT_QUEUE_LENGTH", 0x0002020E,
"OID_802_3_PERMANENT_ADDRESS", 0x01010101,
"OID_802_3_CURRENT_ADDRESS", 0x01010102,
"OID_802_3_MULTICAST_LIST", 0x01010103,
"OID_802_3_MAXIMUM_LIST_SIZE", 0x01010104,
"OID_802_3_RCV_ERROR_ALIGNMENT", 0x01020101,
"OID_802_3_XMIT_ONE_COLLISION", 0x01020102,
"OID_802_3_XMIT_MORE_COLLISIONS", 0x01020103,
"OID_802_3_XMIT_DEFERRED", 0x01020201,
"OID_802_3_XMIT_MAX_COLLISIONS", 0x01020202,
"OID_802_3_RCV_OVERRUN", 0x01020203,
"OID_802_3_XMIT_UNDERRUN", 0x01020204,
"OID_802_3_XMIT_HEARTBEAT_FAILURE", 0x01020205,
"OID_802_3_XMIT_TIMES_CRS_LOST", 0x01020206,
"OID_802_3_XMIT_LATE_COLLISIONS", 0x01020207,
"OID_802_3_PRIORITY", 0x01020208,
"OID_802_5_PERMANENT_ADDRESS", 0x02010101,
"OID_802_5_CURRENT_ADDRESS", 0x02010102,
"OID_802_5_CURRENT_FUNCTIONAL", 0x02010103,
"OID_802_5_CURRENT_GROUP", 0x02010104,
"OID_802_5_LAST_OPEN_STATUS", 0x02010105,
"OID_802_5_CURRENT_RING_STATUS", 0x02010106,
"OID_802_5_CURRENT_RING_STATE", 0x02010107,
"OID_802_5_LINE_ERRORS", 0x02020101,
"OID_802_5_LOST_FRAMES", 0x02020102,
"OID_802_5_BURST_ERRORS", 0x02020201,
"OID_802_5_AC_ERRORS", 0x02020202,
"OID_802_5_ABORT_DELIMETERS", 0x02020203,
"OID_802_5_FRAME_COPIED_ERRORS", 0x02020204,
"OID_802_5_FREQUENCY_ERRORS", 0x02020205,
"OID_802_5_TOKEN_ERRORS", 0x02020206,
"OID_802_5_INTERNAL_ERRORS", 0x02020207,
"OID_FDDI_LONG_PERMANENT_ADDR", 0x03010101,
"OID_FDDI_LONG_CURRENT_ADDR", 0x03010102,
"OID_FDDI_LONG_MULTICAST_LIST", 0x03010103,
"OID_FDDI_LONG_MAX_LIST_SIZE", 0x03010104,
"OID_FDDI_SHORT_PERMANENT_ADDR", 0x03010105,
"OID_FDDI_SHORT_CURRENT_ADDR", 0x03010106,
"OID_FDDI_SHORT_MULTICAST_LIST", 0x03010107,
"OID_FDDI_SHORT_MAX_LIST_SIZE", 0x03010108,
"OID_FDDI_ATTACHMENT_TYPE", 0x03020101,
"OID_FDDI_UPSTREAM_NODE_LONG", 0x03020102,
"OID_FDDI_DOWNSTREAM_NODE_LONG", 0x03020103,
"OID_FDDI_FRAME_ERRORS", 0x03020104,
"OID_FDDI_FRAMES_LOST", 0x03020105,
"OID_FDDI_RING_MGT_STATE", 0x03020106,
"OID_FDDI_LCT_FAILURES", 0x03020107,
"OID_FDDI_LEM_REJECTS", 0x03020108,
"OID_FDDI_LCONNECTION_STATE", 0x03020109,
"OID_FDDI_SMT_STATION_ID", 0x03030201,
"OID_FDDI_SMT_OP_VERSION_ID", 0x03030202,
"OID_FDDI_SMT_HI_VERSION_ID", 0x03030203,
"OID_FDDI_SMT_LO_VERSION_ID", 0x03030204,
"OID_FDDI_SMT_MANUFACTURER_DATA", 0x03030205,
"OID_FDDI_SMT_USER_DATA", 0x03030206,
"OID_FDDI_SMT_MIB_VERSION_ID", 0x03030207,
"OID_FDDI_SMT_MAC_CT", 0x03030208,
"OID_FDDI_SMT_NON_MASTER_CT", 0x03030209,
"OID_FDDI_SMT_MASTER_CT", 0x0303020A,
"OID_FDDI_SMT_AVAILABLE_PATHS", 0x0303020B,
"OID_FDDI_SMT_CONFIG_CAPABILITIES", 0x0303020C,
"OID_FDDI_SMT_CONFIG_POLICY", 0x0303020D,
"OID_FDDI_SMT_CONNECTION_POLICY", 0x0303020E,
"OID_FDDI_SMT_T_NOTIFY", 0x0303020F,
"OID_FDDI_SMT_STAT_RPT_POLICY", 0x03030210,
"OID_FDDI_SMT_TRACE_MAX_EXPIRATION", 0x03030211,
"OID_FDDI_SMT_PORT_INDEXES", 0x03030212,
"OID_FDDI_SMT_MAC_INDEXES", 0x03030213,
"OID_FDDI_SMT_BYPASS_PRESENT", 0x03030214,
"OID_FDDI_SMT_ECM_STATE", 0x03030215,
"OID_FDDI_SMT_CF_STATE", 0x03030216,
"OID_FDDI_SMT_HOLD_STATE", 0x03030217,
"OID_FDDI_SMT_REMOTE_DISCONNECT_FLAG", 0x03030218,
"OID_FDDI_SMT_STATION_STATUS", 0x03030219,
"OID_FDDI_SMT_PEER_WRAP_FLAG", 0x0303021A,
"OID_FDDI_SMT_MSG_TIME_STAMP", 0x0303021B,
"OID_FDDI_SMT_TRANSITION_TIME_STAMP", 0x0303021C,
"OID_FDDI_SMT_SET_COUNT", 0x0303021D,
"OID_FDDI_SMT_LAST_SET_STATION_ID", 0x0303021E,
"OID_FDDI_MAC_FRAME_STATUS_FUNCTIONS", 0x0303021F,
"OID_FDDI_MAC_BRIDGE_FUNCTIONS", 0x03030220,
"OID_FDDI_MAC_T_MAX_CAPABILITY", 0x03030221,
"OID_FDDI_MAC_TVX_CAPABILITY", 0x03030222,
"OID_FDDI_MAC_AVAILABLE_PATHS", 0x03030223,
"OID_FDDI_MAC_CURRENT_PATH", 0x03030224,
"OID_FDDI_MAC_UPSTREAM_NBR", 0x03030225,
"OID_FDDI_MAC_DOWNSTREAM_NBR", 0x03030226,
"OID_FDDI_MAC_OLD_UPSTREAM_NBR", 0x03030227,
"OID_FDDI_MAC_OLD_DOWNSTREAM_NBR", 0x03030228,
"OID_FDDI_MAC_DUP_ADDRESS_TEST", 0x03030229,
"OID_FDDI_MAC_REQUESTED_PATHS", 0x0303022A,
"OID_FDDI_MAC_DOWNSTREAM_PORT_TYPE", 0x0303022B,
"OID_FDDI_MAC_INDEX", 0x0303022C,
"OID_FDDI_MAC_SMT_ADDRESS", 0x0303022D,
"OID_FDDI_MAC_LONG_GRP_ADDRESS", 0x0303022E,
"OID_FDDI_MAC_SHORT_GRP_ADDRESS", 0x0303022F,
"OID_FDDI_MAC_T_REQ", 0x03030230,
"OID_FDDI_MAC_T_NEG", 0x03030231,
"OID_FDDI_MAC_T_MAX", 0x03030232,
"OID_FDDI_MAC_TVX_VALUE", 0x03030233,
"OID_FDDI_MAC_T_PRI0", 0x03030234,
"OID_FDDI_MAC_T_PRI1", 0x03030235,
"OID_FDDI_MAC_T_PRI2", 0x03030236,
"OID_FDDI_MAC_T_PRI3", 0x03030237,
"OID_FDDI_MAC_T_PRI4", 0x03030238,
"OID_FDDI_MAC_T_PRI5", 0x03030239,
"OID_FDDI_MAC_T_PRI6", 0x0303023A,
"OID_FDDI_MAC_FRAME_CT", 0x0303023B,
"OID_FDDI_MAC_COPIED_CT", 0x0303023C,
"OID_FDDI_MAC_TRANSMIT_CT", 0x0303023D,
"OID_FDDI_MAC_TOKEN_CT", 0x0303023E,
"OID_FDDI_MAC_ERROR_CT", 0x0303023F,