完全免费提供ipsec驱动源代码!!!

来源:互联网 发布:江宁区高新园 网络问政 编辑:程序博客网 时间:2024/05/08 00:56

完全免费提供ipsec驱动源代码!!!

看看有没有识货的:)

e-mail:yongliliu@163.net
QQ:33826310

//-----------------------------------------------------------------------------

免费第一个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,

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

今天发布protocol.c
#include "precomp.h"
#include "pgpNetKernel.h"
#include "pgpNetKernelXChng.h"

#include "stdio.h"

#pragma hdrstop

#define MAX_PACKET_POOL_SIZE 0x0000FFFF
#define MIN_PACKET_POOL_SIZE 0x000000FF

void
PtBindAdapter(
OUT PNDIS_STATUS Status,
IN NDIS_HANDLE BindContext,
IN PNDIS_STRING DeviceName,
IN PVOID SystemSpecific1,
IN PVOID SystemSpecific2
)
/*++

Routine Description:

Called by NDIS to bind to a miniport below.

Arguments:

Status - Return status of bind here.
BindContext - Can be passed to NdisCompleteBindAdapter if this call is pended.
DeviceName - Device name to bind to. This is passed to NdisOpenAdapter.
SystemSpecific1 - Can be passed to NdisOpenProtocolConfiguration to read per-binding information
SystemSpecific2 - Unused

Return Value:

NDIS_STATUS_PENDING if this call is pended. In this case call NdisCompleteBindAdapter
to complete.
Anything else Completes this call synchronously

--*/
{
NDIS_HANDLE ConfigHandle = NULL;
PNDIS_CONFIGURATION_PARAMETER Param;
NDIS_STRING DeviceStr = NDIS_STRING_CONST("UpperBindings");
PADAPT pAdapt = NULL;
NDIS_STATUS Sts;
UINT MediumIndex;
ULONG TotalSize;

UNREFERENCED_PARAMETER(BindContext);
UNREFERENCED_PARAMETER(SystemSpecific2);

DBGPRINT(("==> Protocol BindAdapter/n"));

do
{
//
// Access the configuration section for our binding-specific
// parameters.
//
NdisOpenProtocolConfiguration(Status,
&ConfigHandle,
SystemSpecific1);

if (*Status != NDIS_STATUS_SUCCESS)
{
break;
}

//
// Read the "UpperBindings" reserved key that contains a list
// of device names representing our miniport instances corresponding
// to this lower binding. Since this is a 1:1 IM driver, this key
// contains exactly one name.
//
// If we want to implement a N:1 mux driver (N adapter instances
// over a single lower binding), then UpperBindings will be a
// MULTI_SZ containing a list of device names - we would loop through
// this list, calling NdisIMInitializeDeviceInstanceEx once for
// each name in it.
//
NdisReadConfiguration(Status,
&Param,
ConfigHandle,
&DeviceStr,
NdisParameterString);
if (*Status != NDIS_STATUS_SUCCESS)
{
break;
}

//
// Allocate memory for the Adapter structure. This represents both the
// protocol context as well as the adapter structure when the miniport
// is initialized.
//
// In addition to the base structure, allocate space for the device
// instance string.
//
TotalSize = sizeof(ADAPT) + Param->ParameterData.StringData.MaximumLength;

// BEGIN_PTUSERIO
//
// Allocate Space For Lower Adapter Name
//
TotalSize += DeviceName->MaximumLength;
// END_PTUSERIO

NdisAllocateMemoryWithTag(&pAdapt, TotalSize, TAG);

if (pAdapt == NULL)
{
*Status = NDIS_STATUS_RESOURCES;
break;
}

//
// Initialize the adapter structure. We copy in the IM device
// name as well, because we may need to use it in a call to
// NdisIMCancelInitializeDeviceInstance. The string returned
// by NdisReadConfiguration is active (i.e. available) only
// for the duration of this call to our BindAdapter handler.
//
NdisZeroMemory(pAdapt, TotalSize);
/*
pAdapt = AllocateVpnAdapter();
if (pAdapt == NULL)
{
*Status = NDIS_STATUS_RESOURCES;
break;
}
*/
pAdapt->DeviceName.MaximumLength = Param->ParameterData.StringData.MaximumLength;
pAdapt->DeviceName.Length = Param->ParameterData.StringData.Length;
pAdapt->DeviceName.Buffer = (PWCHAR)((ULONG_PTR)pAdapt + sizeof(ADAPT));
NdisMoveMemory(pAdapt->DeviceName.Buffer,
Param->ParameterData.StringData.Buffer,
Param->ParameterData.StringData.Length);


// BEGIN_PTUSERIO
//
// Initialize Lower Adapter Name
// -----------------------------
// Space for lower adapter's name immediately follows our virtual
// adapter's name.
//
pAdapt->LowerDeviceName.MaximumLength = DeviceName->MaximumLength;
pAdapt->LowerDeviceName.Length = DeviceName->Length;

pAdapt->LowerDeviceName.Buffer =
(PWCHAR)((ULONG_PTR)pAdapt
+ sizeof(ADAPT)
+ pAdapt->DeviceName.MaximumLength
);

NdisMoveMemory(
pAdapt->LowerDeviceName.Buffer,
DeviceName->Buffer,
DeviceName->Length
);

//
// Add Protocol's Reference To Adapter Adapter
//
PtRefAdapter( pAdapt );
// END_PTUSERIO


NdisInitializeEvent(&pAdapt->Event);
NdisAllocateSpinLock(&pAdapt->general_lock);

//
// Allocate a packet pool for sends. We need this to pass sends down.
// We cannot use the same packet descriptor that came down to our send
// handler (see also NDIS 5.1 packet stacking).
//
/*
NdisAllocatePacketPoolEx(Status,
&pAdapt->SendPacketPoolHandle,
MIN_PACKET_POOL_SIZE,
MAX_PACKET_POOL_SIZE - MIN_PACKET_POOL_SIZE,
sizeof(SEND_RSVD));
*/
NdisAllocatePacketPool(Status,
&pAdapt->SendPacketPoolHandle,
PACKET_POOL_SIZE,
PROTOCOL_RESERVED_LENGTH);
if (*Status != NDIS_STATUS_SUCCESS)
{
break;
}

//
// Allocate a packet pool for receives. We need this to indicate receives.
// Same consideration as sends (see also NDIS 5.1 packet stacking).
//
/*
NdisAllocatePacketPoolEx(Status,
&pAdapt->RecvPacketPoolHandle,
MIN_PACKET_POOL_SIZE,
MAX_PACKET_POOL_SIZE - MIN_PACKET_POOL_SIZE,
PROTOCOL_RESERVED_SIZE_IN_PACKET);
*/
NdisAllocatePacketPool(Status,
&pAdapt->RecvPacketPoolHandle,
PACKET_POOL_SIZE,
PROTOCOL_RESERVED_LENGTH);
if (*Status != NDIS_STATUS_SUCCESS)
{
break;
}
//add
NdisAllocateBufferPool(Status, &pAdapt->buffer_pool, BUFFER_POOL_SIZE);

if (*Status != NDIS_STATUS_SUCCESS)
{
break;
}
//end
//
// Now open the adapter below and complete the initialization
//
NdisOpenAdapter(Status,
&Sts,
&pAdapt->BindingHandle,
&MediumIndex,
MediumArray,
sizeof(MediumArray)/sizeof(NDIS_MEDIUM),
PGPnetDriver.NdisProtocolHandle,
pAdapt,
DeviceName,
0,
NULL);

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

if (*Status != NDIS_STATUS_SUCCESS)
{
break;
}

//modify
pAdapt->media = MediumArray[MediumIndex];
//end
//
// Now ask NDIS to initialize our miniport (upper) edge.
// Set the flag below to synchronize with a possible call
// to our protocol Unbind handler that may come in before
// our miniport initialization happens.
//
pAdapt->MiniportInitPending = TRUE;
NdisInitializeEvent(&pAdapt->MiniportInitEvent);

*Status = NdisIMInitializeDeviceInstanceEx(PGPnetDriver.NdisMacHandle,
&pAdapt->DeviceName,
pAdapt);

if (*Status != NDIS_STATUS_SUCCESS)
{
DBGPRINT(("BindAdapter: Adapt %p, IMInitializeDeviceInstance error %x/n",
pAdapt, *Status));
break;
}

} while(FALSE);

//
// Close the configuration handle now - see comments above with
// the call to NdisIMInitializeDeviceInstanceEx.
//
if (ConfigHandle != NULL)
{
NdisCloseConfiguration(ConfigHandle);
}

if (*Status != NDIS_STATUS_SUCCESS)
{
if (pAdapt != NULL)
{
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 Protocol's Reference To The Adapter
//
PtDerefAdapter( pAdapt );
// END_PTUSERIO

pAdapt = NULL;
}
}

DBGPRINT(("<== Protocol BindAdapter: pAdapt %p, Status %x/n", pAdapt, *Status));
}


VOID
PtOpenAdapterComplete(
IN NDIS_HANDLE ProtocolBindingContext,
IN NDIS_STATUS Status,
IN NDIS_STATUS OpenErrorStatus
)
/*++

Routine Description:

Completion routine for NdisOpenAdapter issued from within the PtBindAdapter. Simply
unblock the caller.

Arguments:

ProtocolBindingContext Pointer to the adapter
Status Status of the NdisOpenAdapter call
OpenErrorStatus Secondary status(ignored by us).

Return Value:

None

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

UNREFERENCED_PARAMETER(OpenErrorStatus);

DBGPRINT(("==> PtOpenAdapterComplete: Adapt %p, Status %x/n", pAdapt, Status));
pAdapt->Status = Status;
NdisSetEvent(&pAdapt->Event);
}


VOID
PtUnbindAdapter(
OUT PNDIS_STATUS Status,
IN NDIS_HANDLE ProtocolBindingContext,
IN NDIS_HANDLE UnbindContext
)
/*++

Routine Description:

Called by NDIS when we are required to unbind to the adapter below.
This functions shares functionality with the miniport's HaltHandler.
The code should ensure that NdisCloseAdapter and NdisFreeMemory is called
only once between the two functions

Arguments:

Status Placeholder for return status
ProtocolBindingContext Pointer to the adapter structure
UnbindContext Context for NdisUnbindComplete() if this pends

Return Value:

Status for NdisIMDeinitializeDeviceContext

--*/
{
PADAPT pAdapt =(PADAPT)ProtocolBindingContext;
NDIS_STATUS LocalStatus;

UNREFERENCED_PARAMETER(UnbindContext);

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

//
// Set the flag that the miniport below is unbinding, so the request handlers will
// fail any request comming later
//
NdisAcquireSpinLock(&pAdapt->general_lock);
pAdapt->UnbindingInProcess = TRUE;

if (pAdapt->QueuedRequest == TRUE)
{
pAdapt->QueuedRequest = FALSE;
NdisReleaseSpinLock(&pAdapt->general_lock);

PtRequestComplete(pAdapt,
&pAdapt->Request,
NDIS_STATUS_FAILURE );

}
else
{
NdisReleaseSpinLock(&pAdapt->general_lock);
}

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

#ifndef WIN9X
//
// Check if we had called NdisIMInitializeDeviceInstanceEx and
// we are awaiting a call to MiniportInitialize.
//
if (pAdapt->MiniportInitPending == TRUE)
{
//
// Try to cancel the pending IMInit process.
//
LocalStatus = NdisIMCancelInitializeDeviceInstance(
PGPnetDriver.NdisMacHandle,
&pAdapt->DeviceName);

if (LocalStatus == NDIS_STATUS_SUCCESS)
{
//
// Successfully cancelled IM Initialization; our
// Miniport Initialize routine will not be called
// for this device.
//
pAdapt->MiniportInitPending = FALSE;
ASSERT(pAdapt->MiniportHandle == NULL);
}
else
{
//
// Our Miniport Initialize routine will be called
// (may be running on another thread at this time).
// Wait for it to finish.
//
NdisWaitEvent(&pAdapt->MiniportInitEvent, 0);
ASSERT(pAdapt->MiniportInitPending == FALSE);
}

}
#endif // !WIN9X

//
// Call NDIS to remove our device-instance. We do most of the work
// inside the HaltHandler.
//
// The Handle will be NULL if our miniport Halt Handler has been called or
// if the IM device was never initialized
//

if (pAdapt->MiniportHandle != NULL)
{
*Status = NdisIMDeInitializeDeviceInstance(pAdapt->MiniportHandle);

if (*Status != NDIS_STATUS_SUCCESS)
{
*Status = NDIS_STATUS_FAILURE;
}
}
else
{
//
// We need to do some work here.
// Close the binding below us
// and release the memory allocated.
//
if(pAdapt->BindingHandle != NULL)
{
NdisResetEvent(&pAdapt->Event);

NdisCloseAdapter(Status, pAdapt->BindingHandle);

//
// Wait for it to complete
//
if(*Status == NDIS_STATUS_PENDING)
{
NdisWaitEvent(&pAdapt->Event, 0);
*Status = pAdapt->Status;
}
pAdapt->BindingHandle = NULL;
}
else
{
//
// Both Our MiniportHandle and Binding Handle should not be NULL.
//
*Status = NDIS_STATUS_FAILURE;
ASSERT(0);
}

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

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

VOID
PtUnloadProtocol(
VOID
)
{
NDIS_STATUS Status;

if (PGPnetDriver.NdisProtocolHandle != NULL)
{
NdisDeregisterProtocol(&Status, PGPnetDriver.NdisProtocolHandle);
PGPnetDriver.NdisProtocolHandle = NULL;
}

DBGPRINT(("PtUnloadProtocol: done!/n"));
}



VOID
PtCloseAdapterComplete(
IN NDIS_HANDLE ProtocolBindingContext,
IN NDIS_STATUS Status
)
/*++

Routine Description:

Completion for the CloseAdapter call.

Arguments:

ProtocolBindingContext Pointer to the adapter structure
Status Completion status

Return Value:

None.

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

DBGPRINT(("CloseAdapterComplete: Adapt %p, Status %x/n", pAdapt, Status));
pAdapt->Status = Status;
NdisSetEvent(&pAdapt->Event);
}


VOID
PtResetComplete(
IN NDIS_HANDLE ProtocolBindingContext,
IN NDIS_STATUS Status
)
/*++

Routine Description:

Completion for the reset.

Arguments:

ProtocolBindingContext Pointer to the adapter structure
Status Completion status

Return Value:

None.

--*/
{

UNREFERENCED_PARAMETER(ProtocolBindingContext);
UNREFERENCED_PARAMETER(Status);
//
// We never issue a reset, so we should not be here.
//
ASSERT(0);
}


VOID
PtRequestComplete(
IN NDIS_HANDLE ProtocolBindingContext,
IN PNDIS_REQUEST NdisRequest,
IN NDIS_STATUS Status
)
/*++

Routine Description:

Completion handler for the previously posted request. All OIDS
are completed by and sent to the same miniport that they were requested for.
If Oid == OID_PNP_QUERY_POWER then the data structure needs to returned with all entries =
NdisDeviceStateUnspecified

Arguments:

ProtocolBindingContext Pointer to the adapter structure
NdisRequest The posted request
Status Completion status

Return Value:

None

--*/
{
PADAPT pAdapt = (PADAPT)ProtocolBindingContext;
NDIS_OID Oid = pAdapt->Request.DATA.SET_INFORMATION.Oid;

// BEGIN_PTUSERIO
//
// Handle Local NDIS Requests
// --------------------------
// Here we handle NDIS requests that do not originate from the miniport.
//
// Typically, these are requests that were initiated from user-mode but
// could also be requests initiated autonomously by the NDIS IM driver.
//
if( NdisRequest != &(pAdapt->Request) )
{
PNDIS_REQUEST_EX pLocalRequest = (PNDIS_REQUEST_EX )NdisRequest;

(*pLocalRequest->RequestCompleteHandler )( pAdapt, pLocalRequest, Status );

return;
}
// END_PTUSERIO


//
// Since our request is not outstanding anymore
//
ASSERT(pAdapt->OutstandingRequests == TRUE);

pAdapt->OutstandingRequests = FALSE;

//
// Complete the Set or Query, and fill in the buffer for OID_PNP_CAPABILITIES, if need be.
//
switch (NdisRequest->RequestType)
{
case NdisRequestQueryInformation:

//
// We never pass OID_PNP_QUERY_POWER down.
//
ASSERT(Oid != OID_PNP_QUERY_POWER);

if ((Oid == OID_PNP_CAPABILITIES) && (Status == NDIS_STATUS_SUCCESS))
{
MPQueryPNPCapabilities(pAdapt, &Status);
}
*pAdapt->BytesReadOrWritten = NdisRequest->DATA.QUERY_INFORMATION.BytesWritten;
*pAdapt->BytesNeeded = NdisRequest->DATA.QUERY_INFORMATION.BytesNeeded;

if ((Oid == OID_GEN_MAC_OPTIONS) && (Status == NDIS_STATUS_SUCCESS))
{
//
// Remove the no-loopback bit from mac-options. In essence we are
// telling NDIS that we can handle loopback. We don't, but the
// interface below us does. If we do not do this, then loopback
// processing happens both below us and above us. This is wasteful
// at best and if Netmon is running, it will see multiple copies
// of loopback packets when sniffing above us.
//
// Only the lowest miniport is a stack of layered miniports should
// ever report this bit set to NDIS.
//
*(PULONG)NdisRequest->DATA.QUERY_INFORMATION.InformationBuffer &= ~NDIS_MAC_OPTION_NO_LOOPBACK;
}

NdisMQueryInformationComplete(pAdapt->MiniportHandle,
Status);
break;

case NdisRequestSetInformation:

ASSERT( Oid != OID_PNP_SET_POWER);

*pAdapt->BytesReadOrWritten = NdisRequest->DATA.SET_INFORMATION.BytesRead;
*pAdapt->BytesNeeded = NdisRequest->DATA.SET_INFORMATION.BytesNeeded;
NdisMSetInformationComplete(pAdapt->MiniportHandle,
Status);
break;

default:
ASSERT(0);
break;
}

}


VOID
PtStatus(
IN NDIS_HANDLE ProtocolBindingContext,
IN NDIS_STATUS GeneralStatus,
IN PVOID StatusBuffer,
IN UINT StatusBufferSize
)
/*++

Routine Description:

Status handler for the lower-edge(protocol).

Arguments:

ProtocolBindingContext Pointer to the adapter structure
GeneralStatus Status code
StatusBuffer Status buffer
StatusBufferSize Size of the status buffer

Return Value:

None

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

//
// Pass up this indication only if the upper edge miniport is initialized
// and powered on. Also ignore indications that might be sent by the lower
// miniport when it isn't at D0.
//
if ((pAdapt->MiniportHandle != NULL) &&
(pAdapt->MPDeviceState == NdisDeviceStateD0) &&
(pAdapt->PTDeviceState == NdisDeviceStateD0))
{
if ((GeneralStatus == NDIS_STATUS_MEDIA_CONNECT) ||
(GeneralStatus == NDIS_STATUS_MEDIA_DISCONNECT))
{

pAdapt->LastIndicatedStatus = GeneralStatus;
}
NdisMIndicateStatus(pAdapt->MiniportHandle,
GeneralStatus,
StatusBuffer,
StatusBufferSize);
}
//
// Save the last indicated media status
//
else
{
if ((pAdapt->MiniportHandle != NULL) &&
((GeneralStatus == NDIS_STATUS_MEDIA_CONNECT) ||
(GeneralStatus == NDIS_STATUS_MEDIA_DISCONNECT)))
{
pAdapt->LatestUnIndicateStatus = GeneralStatus;
}
}

}


VOID
PtStatusComplete(
IN NDIS_HANDLE ProtocolBindingContext
)
/*++

Routine Description:


Arguments:


Return Value:


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

//
// Pass up this indication only if the upper edge miniport is initialized
// and powered on. Also ignore indications that might be sent by the lower
// miniport when it isn't at D0.
//
if ((pAdapt->MiniportHandle != NULL) &&
(pAdapt->MPDeviceState == NdisDeviceStateD0) &&
(pAdapt->PTDeviceState == NdisDeviceStateD0))
{
NdisMIndicateStatusComplete(pAdapt->MiniportHandle);
}
}


VOID
PtSendComplete(
IN NDIS_HANDLE ProtocolBindingContext,
IN PNDIS_PACKET Packet,
IN NDIS_STATUS Status
)
/*++

Routine Description:

Called by NDIS when the miniport below had completed a send. We should
complete the corresponding upper-edge send this represents.

Arguments:

ProtocolBindingContext - Points to ADAPT structure
Packet - Low level packet being completed
Status - status of send

Return Value:

None

--*/
{
PADAPT pAdapt = (PADAPT)ProtocolBindingContext;
PNDIS_PACKET Pkt;
NDIS_HANDLE PoolHandle;

//add
PPGPNDIS_PACKET pgpPacket;
//end
//add
DBGPRINT(("PtSendComplete function has been called.../n"));
//end

if ( (pgpPacket = PacketRemoveBySrcPacket(pAdapt, &pAdapt->sent_plainpacket_list, Packet)) != NULL )
{
PSEND_RSVD SendRsvd;
SendRsvd = (PSEND_RSVD)(Packet->ProtocolReserved);
Pkt = SendRsvd->OriginalPkt;

#ifndef WIN9X
NdisIMCopySendCompletePerPacketInfo (Pkt, Packet);
#endif

NdisDprFreePacket(Packet);

NdisMSendComplete(pAdapt->MiniportHandle, Pkt, Status);//pgpPacket->Binding->NdisBindingContextFromProtocol

PGPNdisPacketFreeWithBindingContext(pAdapt, pgpPacket);
}
else if ((pgpPacket = PacketRemoveByXformPacket(pAdapt, &pAdapt->sent_ipsecpacket_list, Packet)) != NULL)
{
if ( pgpPacket->fragmentNumber == 2)
{
NdisMSendComplete(pAdapt->MiniportHandle,//pgpPacket->Binding->NdisBindingContextFromProtocol,
pgpPacket->originalPacket,
Status);
}
else if (pgpPacket->fragmentNumber == 1)
{
DBGPRINT(("ProtocolSendComplete. fragment1 sent./n"));
}
else
{
NdisMSendComplete(pAdapt->MiniportHandle,//pgpPacket->Binding->NdisBindingContextFromProtocol
pgpPacket->srcPacket,
Status);
}
PGPNdisPacketFree(pAdapt, pgpPacket);
}
else if ((pgpPacket = PacketRemoveByXformPacket(pAdapt, &pAdapt->outgoing_multiple_ipsecpacket_list, Packet)) != NULL )
{
if (pgpPacket->lastSrcBlock == TRUE)
{
NdisMSendComplete(pAdapt->MiniportHandle, pgpPacket->srcPacket, Status);//pgpPacket->Binding->NdisBindingContextFromProtocol
}
PGPNdisPacketFree(pAdapt, pgpPacket);
}
else
{
//ASSERT(FALSE);
//NdisMSendComplete(pgpPacket->Binding->NdisBindingContextFromProtocol, pgpPacket->srcPacket, Status);
//PGPNdisPacketFree(pAdapt, pgpPacket);
}

//add
ADAPT_DECR_PENDING_SENDS(pAdapt);
//end

/*
#ifdef NDIS51
//
// Packet stacking:
//
// Determine if the packet we are completing is the one we allocated. If so, then
// get the original packet from the reserved area and completed it and free the
// allocated packet. If this is the packet that was sent down to us, then just
// complete it
//
PoolHandle = NdisGetPoolFromPacket(Packet);
if (PoolHandle != pAdapt->SendPacketPoolHandle)
{
//
// We had passed down a packet belonging to the protocol above us.
//
// DBGPRINT(("PtSendComp: Adapt %p, Stacked Packet %p/n", pAdapt, Packet));

NdisMSendComplete(pAdapt->MiniportHandle,
Packet,
Status);
}
else
#endif // NDIS51
{
PSEND_RSVD SendRsvd;

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

#ifndef WIN9X
NdisIMCopySendCompletePerPacketInfo (Pkt, Packet);
#endif

NdisDprFreePacket(Packet);

NdisMSendComplete(pAdapt->MiniportHandle,
Pkt,
Status);
}
//
// Decrease the outstanding send count
//
ADAPT_DECR_PENDING_SENDS(pAdapt);
*/
}


VOID
PtTransferDataComplete(
IN NDIS_HANDLE ProtocolBindingContext,
IN PNDIS_PACKET Packet,
IN NDIS_STATUS Status,
IN UINT BytesTransferred
)
/*++

Routine Description:

Entry point called by NDIS to indicate completion of a call by us
to NdisTransferData.

See notes under SendComplete.

Arguments:

Return Value:

--*/
{
PADAPT pAdapt =(PADAPT)ProtocolBindingContext;
//add
PPGPNDIS_PACKET pgpPacket;
//end
//add
DBGPRINT(("PtTransferDataComplete function has been called.../n"));
//end
//add
if ( (pgpPacket = PacketRemoveBySrcPacket(pAdapt, &pAdapt->sent_plainpacket_list, Packet)) != NULL )
{
NdisMTransferDataComplete(pAdapt->MiniportHandle, Packet, Status, BytesTransferred);//pgpPacket->Binding->NdisBindingContextFromProtocol
PGPNdisPacketFreeWithBindingContext(pAdapt, pgpPacket);
}
else if ( (pgpPacket = PacketRemoveBySrcPacket(pAdapt, &pAdapt->incoming_ipsectransferComplete_wait_list, Packet)) != NULL)
{
if (Status == NDIS_STATUS_SUCCESS)
{
DBGPRINT(("PtTransferDataComplete Status : NDIS_STATUS_SUCCESS/n"));
PGPnetAdjustTransferCompletePacket(pgpPacket);
PacketEnqueue(pAdapt, &pAdapt->incoming_indicateComplete_wait_list, pgpPacket);
}
else
{
DBGPRINT(("PtTransferDataComplete Status : !NDIS_STATUS_SUCCESS/n"));
PGPNdisPacketFreeSrcPacket(pAdapt, pgpPacket);
}
}
else
{
ASSERT(FALSE);
}

//end
/*
if(pAdapt->MiniportHandle)
{
NdisMTransferDataComplete(pAdapt->MiniportHandle,
Packet,
Status,
BytesTransferred);
}
*/
}


NDIS_STATUS
PtReceive(
IN NDIS_HANDLE ProtocolBindingContext,
IN NDIS_HANDLE MacReceiveContext,
IN PVOID HeaderBuffer,
IN UINT HeaderBufferSize,
IN PVOID LookAheadBuffer,
IN UINT LookAheadBufferSize,
IN UINT PacketSize
)
/*++

Routine Description:

Handle receive data indicated up by the miniport below. We pass
it along to the protocol above us.

If the miniport below indicates packets, NDIS would more
likely call us at our ReceivePacket handler. However we
might be called here in certain situations even though
the miniport below has indicated a receive packet, e.g.
if the miniport had set packet status to NDIS_STATUS_RESOURCES.

Arguments:



Return Value:

NDIS_STATUS_SUCCESS if we processed the receive successfully,
NDIS_STATUS_XXX error code if we discarded it.

--*/
{
PADAPT pAdapt = (PADAPT)ProtocolBindingContext;
PNDIS_PACKET MyPacket, Packet;
NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
//add
USHORT eth_header_len;
USHORT eth_protocol;
PETHERNET_HEADER eth_header;
PIP_HEADER ip_header;
PUDP_HEADER udp_header = 0;
PGPnetPMStatus pmstatus;
//end

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

if ((!pAdapt->MiniportHandle) || (pAdapt->MPDeviceState > NdisDeviceStateD0))
{
Status = NDIS_STATUS_FAILURE;
}
else do
{
//
// Get at the packet, if any, indicated up by the miniport below.
//
/*
Packet = NdisGetReceivedPacket(pAdapt->BindingHandle, MacReceiveContext);
if (Packet != NULL)
{
//add
DBGPRINT(("NdisGetReceivedPacket function has get a packet.../n"));
//end
//
// The miniport below did indicate up a packet. Use information
// from that packet to construct a new packet to indicate up.
//

#ifdef NDIS51
//
// NDIS 5.1 NOTE: Do not reuse the original packet in indicating
// up a receive, even if there is sufficient packet stack space.
// If we had to do so, we would have had to overwrite the
// status field in the original packet to NDIS_STATUS_RESOURCES,
// and it is not allowed for protocols to overwrite this field
// in received packets.
//
#endif // NDIS51

//
// Get a packet off the pool and indicate that up
//
NdisDprAllocatePacket(&Status,
&MyPacket,
pAdapt->RecvPacketPoolHandle);

if (Status == NDIS_STATUS_SUCCESS)
{
//
// Make our packet point to data from the original
// packet. NOTE: this works only because we are
// indicating a receive directly from the context of
// our receive indication. If we need to queue this
// packet and indicate it from another thread context,
// we will also have to allocate a new buffer and copy
// over the packet contents, OOB data and per-packet
// information. This is because the packet data
// is available only for the duration of this
// receive indication call.
//
MyPacket->Private.Head = Packet->Private.Head;
MyPacket->Private.Tail = Packet->Private.Tail;

//
// Get the original packet (it could be the same packet as the
// one received or a different one based on the number of layered
// miniports below) and set it on the indicated packet so the OOB
// data is visible correctly at protocols above.
//
NDIS_SET_ORIGINAL_PACKET(MyPacket, NDIS_GET_ORIGINAL_PACKET(Packet));
NDIS_SET_PACKET_HEADER_SIZE(MyPacket, HeaderBufferSize);

//
// Copy packet flags.
//
NdisGetPacketFlags(MyPacket) = NdisGetPacketFlags(Packet);

//
// Force protocols above to make a copy if they want to hang
// on to data in this packet. This is because we are in our
// Receive handler (not ReceivePacket) and we can't return a
// ref count from here.
//
NDIS_SET_PACKET_STATUS(MyPacket, NDIS_STATUS_RESOURCES);

//
// By setting NDIS_STATUS_RESOURCES, we also know that we can reclaim
// this packet as soon as the call to NdisMIndicateReceivePacket
// returns.
//

NdisMIndicateReceivePacket(pAdapt->MiniportHandle, &MyPacket, 1);

//
// Reclaim the indicated packet. Since we had set its status
// to NDIS_STATUS_RESOURCES, we are guaranteed that protocols
// above are done with it.
//
NdisDprFreePacket(MyPacket);

break;
}
}

else
*/
{
//
// The miniport below us uses the old-style (not packet)
// receive indication. Fall through.
//

if (LookAheadBufferSize < (sizeof(IP_HEADER)) ) {
Status = NDIS_STATUS_NOT_ACCEPTED;
goto failout;
}

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

eth_header = (PETHERNET_HEADER) HeaderBuffer;
eth_protocol = *((PUSHORT)(ð_header->eth_protocolType[0]));

if (eth_protocol != IPPROT_NET)
{
goto passthrough;
}

eth_header_len = sizeof(ETHERNET_HEADER);

ip_header = (PIP_HEADER) ( (UCHAR*)LookAheadBuffer );

if (ip_header->ip_prot == PROTOCOL_IGMP)
goto passthrough;

if (ip_header->ip_prot == PROTOCOL_ICMP)
{
#ifdef KERNEL_MESSAGE_EMULATION

PGPMESSAGE_CONTEXT *kernelMessageContext;
PGPnetMessageHeader *kernelMessageHeader;
PGPnet_ICMP_Message *icmpMessage;

kernelMessageContext = (PGPMESSAGE_CONTEXT*)(pAdapt->pgpMessage);

kernelMessageHeader = &kernelMessageContext->header;


NdisAcquireSpinLock(&pAdapt->general_lock);

kernelMessageHeader->head++;

if (kernelMessageHeader->head > kernelMessageHeader->maxSlots)
kernelMessageHeader->head = 1;

kernelMessageContext = &kernelMessageContext[kernelMessageHeader->head];

kernelMessageContext->messageType = PGPnetMessageICMPType;

icmpMessage = (PGPnet_ICMP_Message*)&kernelMessageContext->message;

icmpMessage->ip_packets_received = pAdapt->ReceivePackets;

NdisReleaseSpinLock(&pAdapt->general_lock);

PgpEventSet(&pAdapt->pgpEvent);
#endif
}

if ( (ip_header->ip_prot == PROTOCOL_UDP) &&
LookAheadBufferSize >= (sizeof(IP_HEADER) + sizeof(UDP_HEADER)) )
{
udp_header = (PUDP_HEADER) ( (UCHAR*)ip_header + sizeof(IP_HEADER) );
}

if (NdisMedium802_3 == pAdapt->media)
{
//这里的适配器IP地址应该是NDIS通过调用MPSend进行处理获得
DBGPRINT(( "reveive ip_address: 0X%X/n", pAdapt->ip_address ));
if (ip_header->ip_dest != pAdapt->ip_address)
{
DBGPRINT(("the ip_address is not right,passthrough.../n"));
goto passthrough;
}
}

if (ip_header->ip_foff)
{
DBGPRINT(("PGPnetPMNeedTransformLight to be called.../n"));
pmstatus = PGPnetPMNeedTransformLight(PGPnetDriver.PolicyManagerHandle,
ip_header->ip_src,
TRUE,
pAdapt);
}
else
{
DBGPRINT(("PGPnetPMNeedTransform to be called.../n"));
pmstatus = PGPnetPMNeedTransform(PGPnetDriver.PolicyManagerHandle,
ip_header->ip_src,
(PGPUInt16)(udp_header ? udp_header->dest_port : 0),
TRUE,
LookAheadBuffer,
LookAheadBufferSize,
0,
pAdapt);
}

if ( kPGPNetPMPacketClear == pmstatus )
{
DBGPRINT(("We receive a packet need to passthrough.../n"));
goto passthrough;
}

if ( kPGPNetPMPacketEncrypt != pmstatus )
{
DBGPRINT(("We receive a packet need to reject.../n"));
Status = NDIS_STATUS_NOT_ACCEPTED;
goto failout;
}

DBGPRINT(("We receive a packet need to decrypt.../n"));
//add
pAdapt->IndicateRcvComplete = TRUE;
// pAdapt->ipsec_incoming = TRUE;
//end
Status = QueueForTransferComplete(pAdapt,
MacReceiveContext,
HeaderBuffer,
HeaderBufferSize,
LookAheadBuffer,
LookAheadBufferSize,
PacketSize);

return Status;
//end
}

//
// Fall through if the miniport below us has either not
// indicated a packet or we could not allocate one
//
} while(FALSE);

//add
passthrough:

pAdapt->IndicateRcvComplete = TRUE;
// pAdapt->ipsec_incoming = FALSE;

ProtocolIndicateReceive(pAdapt,
MacReceiveContext,
HeaderBuffer,
HeaderBufferSize,
LookAheadBuffer,
LookAheadBufferSize,
PacketSize);

Status = NDIS_STATUS_SUCCESS;

pAdapt->ReceivePackets++;

//add
failout:

return Status;
}

VOID ProtocolIndicateReceive(
IN PVPN_ADAPTER pAdapt,
IN NDIS_HANDLE MacContext,
IN PUCHAR HeaderBuffer,
IN UINT HeaderBufferSize,
IN PVOID LookAheadBuffer,
IN UINT LookAheadBufferSize,
IN UINT PacketSize
)
{
NDIS_STATUS Status;

PBINDING_CONTEXT eachBinding;
UINT i;

//add
UINT j,len;
PUCHAR AheadBuffer = (PUCHAR)LookAheadBuffer;
UCHAR hBuffer[1500] = "";
//end

NdisAcquireSpinLock(&pAdapt->general_lock);

eachBinding = (PBINDING_CONTEXT)pAdapt->Bindings.Flink;

for (i = 0; i < pAdapt->BindingNumber; i++)
{
ASSERT(eachBinding);

ASSERT(eachBinding->NdisBindingContextFromProtocol);

NdisReleaseSpinLock(&pAdapt->general_lock);

switch (pAdapt->media)
{
case NdisMedium802_3:
case NdisMediumWan:
//add
if (AheadBuffer[0] == 0X45 && AheadBuffer[9] == 0X06)
{
DBGPRINT(("LookAheadBufferSize:0X%X/n",LookAheadBufferSize));
DBGPRINT(("LookAheadBuffer:/n"));
len = (LookAheadBufferSize>500) ? 500:LookAheadBufferSize;
for (j=0;j sprintf(hBuffer + (2+1)*j,"%2.2X ",AheadBuffer[j]);
DBGPRINT(("%s/n",hBuffer));

DBGPRINT(("PacketSize:0X%X/n",PacketSize));
}
//end
NdisMEthIndicateReceive(pAdapt->MiniportHandle,//eachBinding->NdisBindingContextFromProtocol,
MacContext,
HeaderBuffer,
HeaderBufferSize,
LookAheadBuffer,
LookAheadBufferSize,
PacketSize);
break;

case NdisMedium802_5:
NdisMTrIndicateReceive(pAdapt->MiniportHandle,//eachBinding->NdisBindingContextFromProtocol,
MacContext,
HeaderBuffer,
HeaderBufferSize,
LookAheadBuffer,
LookAheadBufferSize,
PacketSize);
break;

case NdisMediumFddi:
NdisMFddiIndicateReceive(pAdapt->MiniportHandle,//eachBinding->NdisBindingContextFromProtocol,
MacContext,
HeaderBuffer,
HeaderBufferSize,
LookAheadBuffer,
LookAheadBufferSize,
PacketSize);
break;

default:
ASSERT(FALSE);
break;
}
/*
NdisIndicateReceive(&Status,
pAdapt->MiniportHandle,//eachBinding->NdisBindingContextFromProtocol,
MacContext,
HeaderBuffer,
HeaderBufferSize,
LookAheadBuffer,
LookAheadBufferSize,
PacketSize
);
*/
//add
Status = NDIS_STATUS_SUCCESS;
//end
NdisAcquireSpinLock(&pAdapt->general_lock);

if (Status != NDIS_STATUS_NOT_ACCEPTED)
{
pAdapt->unsecuredPacketIndicated = TRUE;
}

eachBinding = (PBINDING_CONTEXT)eachBinding->Next.Flink;
}

NdisReleaseSpinLock(&pAdapt->general_lock);
}


VOID
PtReceiveComplete(
IN NDIS_HANDLE ProtocolBindingContext
)
/*++

Routine Description:

Called by the adapter below us when it is done indicating a batch of
received packets.

Arguments:

ProtocolBindingContext Pointer to our adapter structure.

Return Value:

None

--*/
{
PADAPT pAdapt =(PADAPT)ProtocolBindingContext;
//add
PPGPNDIS_PACKET pgpPacket;
UINT indicated = 0;

DBGPRINT(("PtReceiveComplete function has been called.../n"));
//end
if ((pAdapt->MiniportHandle != NULL) && (pAdapt->IndicateRcvComplete))
// && (pAdapt->MPDeviceState > NdisDeviceStateD0)
{
NdisAcquireSpinLock(&pAdapt->general_lock);

if (pAdapt->indicate_busy == FALSE)
{
pAdapt->indicate_busy = TRUE;
NdisReleaseSpinLock(&pAdapt->general_lock);

while ( (pgpPacket = PacketDequeue(pAdapt, &pAdapt->incoming_indicateComplete_wait_list)) != NULL )
{
NDIS_STATUS status;
status = TransformAndIndicate(pAdapt, pgpPacket);
if (status == NDIS_STATUS_SUCCESS)
{
PGPNdisPacketFreeSrcPacket(pAdapt, pgpPacket);
}
if (status == NDIS_STATUS_SUCCESS)
indicated++;
}

if (pAdapt->receive_fragmented)
{
switch (pAdapt->media)
{
case NdisMedium802_3:
case NdisMediumWan:
NdisMEthIndicateReceiveComplete(pAdapt->MiniportHandle);
break;

case NdisMedium802_5:
NdisMTrIndicateReceiveComplete(pAdapt->MiniportHandle);
break;

case NdisMediumFddi:
NdisMFddiIndicateReceiveComplete(pAdapt->MiniportHandle);
break;

default:
ASSERT(FALSE);
break;
}
//NdisIndicateReceiveComplete(pAdapt->NdisBindingContextFromProtocol);
}

if ( indicated > 0 || pAdapt->unsecuredPacketIndicated)
{
// If we have an unsecured packet indicateComplete pending. Do a indicateReceiveComplete
// Note, if we indicate a secured packet, we should also indicate a receiveComplete.
// Cause that's the last chance we do it. Or is it?

pAdapt->unsecuredPacketIndicated = FALSE;
//NdisIndicateReceiveComplete(adapter->NdisBindingContextFromProtocol);
ProtocolIndicateReceiveComplete(pAdapt);
}

if (pAdapt->receive_fragmented)
{
while ( (pgpPacket = PacketDequeue(pAdapt, &pAdapt->incoming_fragment_indicateComplete_wait_list)) != NULL )
{
PGPNdisPacketFreeSrcPacket(pAdapt, pgpPacket);
}
pAdapt->receive_fragmented = FALSE;
}

NdisAcquireSpinLock(&pAdapt->general_lock);
pAdapt->indicate_busy = FALSE;
}
NdisReleaseSpinLock(&pAdapt->general_lock);
}
pAdapt->IndicateRcvComplete = FALSE;
}

VOID ProtocolIndicateReceiveComplete(
IN PVPN_ADAPTER pAdapt
)
{
PBINDING_CONTEXT eachBinding;
UINT i;

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

NdisAcquireSpinLock(&pAdapt->general_lock);

eachBinding = (PBINDING_CONTEXT)pAdapt->Bindings.Flink;

DBGPRINT(("BindingNumber :0X%X/n",pAdapt->BindingNumber));

for (i= 0; i< pAdapt->BindingNumber; i++)
{
ASSERT(eachBinding);

ASSERT(eachBinding->NdisBindingContextFromProtocol);

NdisReleaseSpinLock(&pAdapt->general_lock);
//add
switch (pAdapt->media)
{
case NdisMedium802_3:
case NdisMediumWan:
NdisMEthIndicateReceiveComplete(pAdapt->MiniportHandle);//eachBinding->NdisBindingContextFromProtocol
break;

case NdisMedium802_5:
NdisMTrIndicateReceiveComplete(pAdapt->MiniportHandle);//eachBinding->NdisBindingContextFromProtocol
break;

case NdisMediumFddi:
NdisMFddiIndicateReceiveComplete(pAdapt->MiniportHandle);//eachBinding->NdisBindingContextFromProtocol
break;

default:
ASSERT(FALSE);
break;
}
//end
// NdisIndicateReceiveComplete(eachBinding->NdisBindingContextFromProtocol);

NdisAcquireSpinLock(&pAdapt->general_lock);

eachBinding = (PBINDING_CONTEXT)eachBinding->Next.Flink;
}
NdisReleaseSpinLock(&pAdapt->general_lock);
}


INT
PtReceivePacket(
IN NDIS_HANDLE ProtocolBindingContext,
IN PNDIS_PACKET Packet
)
/*++

Routine Description:

ReceivePacket handler. Called by NDIS if the miniport below supports
NDIS 4.0 style receives. Re-package the buffer chain in a new packet
and indicate the new packet to protocols above us. Any context for
packets indicated up must be kept in the MiniportReserved field.

NDIS 5.1 - packet stacking - if there is sufficient "stack space" in
the packet passed to us, we can use the same packet in a receive
indication.

Arguments:

ProtocolBindingContext - Pointer to our adapter structure.
Packet - Pointer to the packet

Return Value:

== 0 -> We are done with the packet
!= 0 -> We will keep the packet and call NdisReturnPackets() this
many times when done.
--*/
{
PADAPT pAdapt =(PADAPT)ProtocolBindingContext;
NDIS_STATUS Status;
PNDIS_PACKET MyPacket;
BOOLEAN Remaining;

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

//
// Drop the packet silently if the upper miniport edge isn't initialized or
// the miniport edge is in low power state
//
if ((!pAdapt->MiniportHandle) || (pAdapt->MPDeviceState > NdisDeviceStateD0))
{
return 0;
}

#ifdef NDIS51
//
// Check if we can reuse the same packet for indicating up.
// See also: PtReceive().
//

(VOID)NdisIMGetCurrentPacketStack(Packet, &Remaining);
if (Remaining)
{
//
// We can reuse "Packet". Indicate it up and be done with it.
//
Status = NDIS_GET_PACKET_STATUS(Packet);
NdisMIndicateReceivePacket(pAdapt->MiniportHandle, &Packet, 1);
return((Status != NDIS_STATUS_RESOURCES) ? 1 : 0);
}
#endif // NDIS51

//
// Get a packet off the pool and indicate that up
//
NdisDprAllocatePacket(&Status,
&MyPacket,
pAdapt->RecvPacketPoolHandle);

if (Status == NDIS_STATUS_SUCCESS)
{
PRECV_RSVD RecvRsvd;

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

MyPacket->Private.Head = Packet->Private.Head;
MyPacket->Private.Tail = Packet->Private.Tail;

//
// Get the original packet (it could be the same packet as the one
// received or a different one based on the number of layered miniports
// below) and set it on the indicated packet so the OOB data is visible
// correctly to protocols above us.
//
NDIS_SET_ORIGINAL_PACKET(MyPacket, NDIS_GET_ORIGINAL_PACKET(Packet));

//
// Set Packet Flags
//
NdisGetPacketFlags(MyPacket) = NdisGetPacketFlags(Packet);

Status = NDIS_GET_PACKET_STATUS(Packet);

NDIS_SET_PACKET_STATUS(MyPacket, Status);
NDIS_SET_PACKET_HEADER_SIZE(MyPacket, NDIS_GET_PACKET_HEADER_SIZE(Packet));

NdisMIndicateReceivePacket(pAdapt->MiniportHandle, &MyPacket, 1);

//
// Check if we had indicated up the packet with NDIS_STATUS_RESOURCES
// NOTE -- do not use NDIS_GET_PACKET_STATUS(MyPacket) for this since
// it might have changed! Use the value saved in the local variable.
//
if (Status == NDIS_STATUS_RESOURCES)
{
//
// Our ReturnPackets handler will not be called for this packet.
// We should reclaim it right here.
//
NdisDprFreePacket(MyPacket);
}

return((Status != NDIS_STATUS_RESOURCES) ? 1 : 0);
}
else
{
//
// We are out of packets. Silently drop it.
//
return(0);
}
}




NDIS_STATUS
PtPNPHandler(
IN NDIS_HANDLE ProtocolBindingContext,
IN PNET_PNP_EVENT pNetPnPEvent
)

/*++
Routine Description:

This is called by NDIS to notify us of a PNP event related to a lower
binding. Based on the event, this dispatches to other helper routines.

NDIS 5.1: forward this event to the upper protocol(s) by calling
NdisIMNotifyPnPEvent.

Arguments:

ProtocolBindingContext - Pointer to our adapter structure. Can be NULL
for "global" notifications

pNetPnPEvent - Pointer to the PNP event to be processed.

Return Value:

NDIS_STATUS code indicating status of event processing.

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

DBGPRINT(("PtPnPHandler: Adapt %p, Event %d/n", pAdapt, pNetPnPEvent->NetEvent));

switch (pNetPnPEvent->NetEvent)
{
case NetEventSetPower:
Status = PtPnPNetEventSetPower(pAdapt, pNetPnPEvent);
break;

case NetEventReconfigure:
Status = PtPnPNetEventReconfigure(pAdapt, pNetPnPEvent);
break;

default:
#ifdef NDIS51
//
// Pass on this notification to protocol(s) above, before
// doing anything else with it.
//
if (pAdapt && pAdapt->MiniportHandle)
{
Status = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent);
}
#else
Status = NDIS_STATUS_SUCCESS;

#endif // NDIS51

break;
}

return Status;
}


NDIS_STATUS
PtPnPNetEventReconfigure(
IN PADAPT pAdapt,
IN PNET_PNP_EVENT pNetPnPEvent
)
/*++
Routine Description:

This routine is called from NDIS to notify our protocol edge of a
reconfiguration of parameters for either a specific binding (pAdapt
is not NULL), or global parameters if any (pAdapt is NULL).

Arguments:

pAdapt - Pointer to our adapter structure.
pNetPnPEvent - the reconfigure event

Return Value:

NDIS_STATUS_SUCCESS

--*/
{
NDIS_STATUS ReconfigStatus = NDIS_STATUS_SUCCESS;
NDIS_STATUS ReturnStatus = NDIS_STATUS_SUCCESS;

do
{
//
// Is this is a global reconfiguration notification ?
//
if (pAdapt == NULL)
{
//
// An important event that causes this notification to us is if
// one of our upper-edge miniport instances was enabled after being
// disabled earlier, e.g. from Device Manager in Win2000. Note that
// NDIS calls this because we had set up an association between our
// miniport and protocol entities by calling NdisIMAssociateMiniport.
//
// Since we would have torn down the lower binding for that miniport,
// we need NDIS' assistance to re-bind to the lower miniport. The
// call to NdisReEnumerateProtocolBindings does exactly that.
//
NdisReEnumerateProtocolBindings (PGPnetDriver.NdisProtocolHandle);
break;
}

#ifdef NDIS51
//
// Pass on this notification to protocol(s) above before doing anything
// with it.
//
if (pAdapt->MiniportHandle)
{
ReturnStatus = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent);
}
#endif // NDIS51

ReconfigStatus = NDIS_STATUS_SUCCESS;

} while(FALSE);

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

#ifdef NDIS51
//
// Overwrite status with what upper-layer protocol(s) returned.
//
ReconfigStatus = ReturnStatus;
#endif

return ReconfigStatus;
}


NDIS_STATUS
PtPnPNetEventSetPower(
IN PADAPT pAdapt,
IN PNET_PNP_EVENT pNetPnPEvent
)
/*++
Routine Description:

This is a notification to our protocol edge of the power state
of the lower miniport. If it is going to a low-power state, we must
wait here for all outstanding sends and requests to complete.

NDIS 5.1: Since we use packet stacking, it is not sufficient to
check usage of our local send packet pool to detect whether or not
all outstanding sends have completed. For this, use the new API
NdisQueryPendingIOCount.

NDIS 5.1: Use the 5.1 API NdisIMNotifyPnPEvent to pass on PnP
notifications to upper protocol(s).

Arguments:

pAdapt - Pointer to the adpater structure
pNetPnPEvent - The Net Pnp Event. this contains the new device state

Return Value:

NDIS_STATUS_SUCCESS or the status returned by upper-layer protocols.

--*/
{
PNDIS_DEVICE_POWER_STATE pDeviceState =(PNDIS_DEVICE_POWER_STATE)(pNetPnPEvent->Buffer);
NDIS_DEVICE_POWER_STATE PrevDeviceState = pAdapt->PTDeviceState;
NDIS_STATUS Status;
NDIS_STATUS ReturnStatus;
#ifdef NDIS51
ULONG PendingIoCount = 0;
#endif // NDIS51

ReturnStatus = NDIS_STATUS_SUCCESS;

//
// Set the Internal Device State, this blocks all new sends or receives
//
NdisAcquireSpinLock(&pAdapt->general_lock);
pAdapt->PTDeviceState = *pDeviceState;

//
// Check if the miniport below is going to a low power state.
//
if (pAdapt->PTDeviceState > NdisDeviceStateD0)
{
//
// If the miniport below is going to standby, fail all incoming requests
//
if (PrevDeviceState == NdisDeviceStateD0)
{
pAdapt->StandingBy = TRUE;
}

NdisReleaseSpinLock(&pAdapt->general_lock);

#ifdef NDIS51
//
// Notify upper layer protocol(s) first.
//
if (pAdapt->MiniportHandle != NULL)
{
ReturnStatus = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent);
}
#endif // NDIS51

//
// Wait for outstanding sends and requests to complete.
//
while (pAdapt->OutstandingSends != 0)
{
NdisMSleep(2);
}

while (pAdapt->OutstandingRequests == TRUE)
{
//
// sleep till outstanding requests complete
//
NdisMSleep(2);
}

//
// If the below miniport is going to low power state, complete the queued request
//
NdisAcquireSpinLock(&pAdapt->general_lock);
if (pAdapt->QueuedRequest)
{
pAdapt->QueuedRequest = FALSE;
NdisReleaseSpinLock(&pAdapt->general_lock);
PtRequestComplete(pAdapt, &pAdapt->Request, NDIS_STATUS_FAILURE);
}
else
{
NdisReleaseSpinLock(&pAdapt->general_lock);
}

ASSERT(NdisPacketPoolUsage(pAdapt->SendPacketPoolHandle) == 0);
ASSERT(pAdapt->OutstandingRequests == FALSE);
}
else
{
//
// If the physical miniport is powering up (from Low power state to D0),
// clear the flag
//
if (PrevDeviceState > NdisDeviceStateD0)
{
pAdapt->StandingBy = FALSE;
}
//
// The device below is being turned on. If we had a request
// pending, send it down now.
//
if (pAdapt->QueuedRequest == TRUE)
{
pAdapt->QueuedRequest = FALSE;

pAdapt->OutstandingRequests = TRUE;
NdisReleaseSpinLock(&pAdapt->general_lock);

NdisRequest(&Status,
pAdapt->BindingHandle,
&pAdapt->Request);

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


#ifdef NDIS51
//
// Pass on this notification to protocol(s) above
//
if (pAdapt->MiniportHandle)
{
ReturnStatus = NdisIMNotifyPnPEvent(pAdapt->MiniportHandle, pNetPnPEvent);
}
#endif // NDIS51

}

return ReturnStatus;
}

 

原创粉丝点击