VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/VBoxNetFlt/win/drv/VBoxNetLwf-win.cpp@ 58651

Last change on this file since 58651 was 58651, checked in by vboxsync, 9 years ago

NetLwf/win: Allocate miniport name buffer from non-paged pool.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 105.3 KB
Line 
1/* $Id: VBoxNetLwf-win.cpp 58651 2015-11-10 16:33:48Z vboxsync $ */
2/** @file
3 * VBoxNetLwf-win.cpp - NDIS6 Bridged Networking Driver, Windows-specific code.
4 */
5/*
6 * Copyright (C) 2014-2015 Oracle Corporation
7 *
8 * This file is part of VirtualBox Open Source Edition (OSE), as
9 * available from http://www.virtualbox.org. This file is free software;
10 * you can redistribute it and/or modify it under the terms of the GNU
11 * General Public License (GPL) as published by the Free Software
12 * Foundation, in version 2 as it comes in the "COPYING" file of the
13 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
14 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
15 */
16#define LOG_GROUP LOG_GROUP_NET_FLT_DRV
17
18//#define VBOXNETLWF_SYNC_SEND
19
20#include <VBox/version.h>
21#include <VBox/err.h>
22#include <iprt/initterm.h>
23#include <iprt/net.h>
24#include <iprt/list.h>
25#include <VBox/intnetinline.h>
26
27/// @todo Not sure why, but can it help with build errors?
28RT_C_DECLS_BEGIN
29/* ntddk.h has a missing #pragma pack(), work around it
30 * see #ifdef VBOX_WITH_WORKAROUND_MISSING_PACK below for detail */
31#define VBOX_WITH_WORKAROUND_MISSING_PACK
32#if (_MSC_VER >= 1400) && !defined(VBOX_WITH_PATCHED_DDK)
33# define _InterlockedExchange _InterlockedExchange_StupidDDKVsCompilerCrap
34# define _InterlockedExchangeAdd _InterlockedExchangeAdd_StupidDDKVsCompilerCrap
35# define _InterlockedCompareExchange _InterlockedCompareExchange_StupidDDKVsCompilerCrap
36# define _InterlockedAddLargeStatistic _InterlockedAddLargeStatistic_StupidDDKVsCompilerCrap
37# define _interlockedbittestandset _interlockedbittestandset_StupidDDKVsCompilerCrap
38# define _interlockedbittestandreset _interlockedbittestandreset_StupidDDKVsCompilerCrap
39# define _interlockedbittestandset64 _interlockedbittestandset64_StupidDDKVsCompilerCrap
40# define _interlockedbittestandreset64 _interlockedbittestandreset64_StupidDDKVsCompilerCrap
41# pragma warning(disable : 4163)
42# ifdef VBOX_WITH_WORKAROUND_MISSING_PACK
43# pragma warning(disable : 4103)
44# endif
45# include <ntddk.h>
46# pragma warning(default : 4163)
47# ifdef VBOX_WITH_WORKAROUND_MISSING_PACK
48# pragma pack()
49# pragma warning(default : 4103)
50# endif
51# undef _InterlockedExchange
52# undef _InterlockedExchangeAdd
53# undef _InterlockedCompareExchange
54# undef _InterlockedAddLargeStatistic
55# undef _interlockedbittestandset
56# undef _interlockedbittestandreset
57# undef _interlockedbittestandset64
58# undef _interlockedbittestandreset64
59# include <ndis.h>
60# include <netioapi.h>
61#else
62# include <ntddk.h>
63# include <netioapi.h>
64/* can include ndis.h right away */
65# include <ndis.h>
66#endif
67#include <mstcpip.h>
68RT_C_DECLS_END
69
70#if 0
71#undef Log
72#define Log(x) DbgPrint x
73#undef LogFlow
74#define LogFlow(x) DbgPrint x
75#endif
76
77/** We have an entirely different structure than the one defined in VBoxNetFltCmn-win.h */
78typedef struct VBOXNETFLTWIN
79{
80 /** filter module context handle */
81 NDIS_HANDLE hModuleCtx;
82 /** IP address change notifier handle */
83 HANDLE hNotifier; /* Must be here as hModuleCtx may already be NULL when vboxNetFltOsDeleteInstance is called */
84} VBOXNETFLTWIN, *PVBOXNETFLTWIN;
85#define VBOXNETFLT_NO_PACKET_QUEUE
86#define VBOXNETFLT_OS_SPECFIC 1
87#include "VBoxNetFltInternal.h"
88
89#include "VBoxNetLwf-win.h"
90#include "VBox/VBoxNetCmn-win.h"
91
92/* Forward declarations */
93FILTER_ATTACH vboxNetLwfWinAttach;
94FILTER_DETACH vboxNetLwfWinDetach;
95FILTER_RESTART vboxNetLwfWinRestart;
96FILTER_PAUSE vboxNetLwfWinPause;
97FILTER_OID_REQUEST vboxNetLwfWinOidRequest;
98FILTER_OID_REQUEST_COMPLETE vboxNetLwfWinOidRequestComplete;
99//FILTER_CANCEL_OID_REQUEST vboxNetLwfWinCancelOidRequest;
100FILTER_STATUS vboxNetLwfWinStatus;
101//FILTER_NET_PNP_EVENT vboxNetLwfWinPnPEvent;
102FILTER_SEND_NET_BUFFER_LISTS vboxNetLwfWinSendNetBufferLists;
103FILTER_SEND_NET_BUFFER_LISTS_COMPLETE vboxNetLwfWinSendNetBufferListsComplete;
104FILTER_RECEIVE_NET_BUFFER_LISTS vboxNetLwfWinReceiveNetBufferLists;
105FILTER_RETURN_NET_BUFFER_LISTS vboxNetLwfWinReturnNetBufferLists;
106KSTART_ROUTINE vboxNetLwfWinInitIdcWorker;
107
108typedef enum {
109 LwfState_Detached = 0,
110 LwfState_Attaching,
111 LwfState_Paused,
112 LwfState_Restarting,
113 LwfState_Running,
114 LwfState_Pausing,
115 LwfState_32BitHack = 0x7fffffff
116} VBOXNETLWFSTATE;
117
118/*
119 * Valid state transitions are:
120 * 1) Disconnected -> Connecting : start the worker thread, attempting to init IDC;
121 * 2) Connecting -> Disconnected : failed to start IDC init worker thread;
122 * 3) Connecting -> Connected : IDC init successful, terminate the worker;
123 * 4) Connecting -> Stopping : IDC init incomplete, but the driver is being unloaded, terminate the worker;
124 * 5) Connected -> Stopping : IDC init was successful, no worker, the driver is being unloaded;
125 *
126 * Driver terminates in Stopping state.
127 */
128typedef enum {
129 LwfIdcState_Disconnected = 0, /* Initial state */
130 LwfIdcState_Connecting, /* Attemping to init IDC, worker thread running */
131 LwfIdcState_Connected, /* Successfully connected to IDC, worker thread terminated */
132 LwfIdcState_Stopping /* Terminating the worker thread and disconnecting IDC */
133} VBOXNETLWFIDCSTATE;
134
135struct _VBOXNETLWF_MODULE;
136
137typedef struct VBOXNETLWFGLOBALS
138{
139 /** synch event used for device creation synchronization */
140 //KEVENT SynchEvent;
141 /** Device reference count */
142 //int cDeviceRefs;
143 /** ndis device */
144 NDIS_HANDLE hDevice;
145 /** device object */
146 PDEVICE_OBJECT pDevObj;
147 /** our filter driver handle */
148 NDIS_HANDLE hFilterDriver;
149 /** lock protecting the module list */
150 NDIS_SPIN_LOCK Lock;
151 /** the head of module list */
152 RTLISTANCHOR listModules;
153 /** IDC initialization state */
154 volatile uint32_t enmIdcState;
155 /** IDC init thread handle */
156 HANDLE hInitIdcThread;
157} VBOXNETLWFGLOBALS, *PVBOXNETLWFGLOBALS;
158
159/**
160 * The (common) global data.
161 */
162static VBOXNETFLTGLOBALS g_VBoxNetFltGlobals;
163/* win-specific global data */
164VBOXNETLWFGLOBALS g_VBoxNetLwfGlobals;
165
166typedef struct _VBOXNETLWF_MODULE {
167 RTLISTNODE node;
168
169 NDIS_HANDLE hFilter;
170 NDIS_HANDLE hPool;
171 PVBOXNETLWFGLOBALS pGlobals;
172 /** Associated instance of NetFlt, one-to-one relationship */
173 PVBOXNETFLTINS pNetFlt; /// @todo Consider automic access!
174 /** Module state as described in http://msdn.microsoft.com/en-us/library/windows/hardware/ff550017(v=vs.85).aspx */
175 volatile uint32_t enmState; /* No lock needed yet, atomic should suffice. */
176 /** Mutex to prevent pausing while transmitting on behalf of NetFlt */
177 NDIS_MUTEX InTransmit;
178#ifdef VBOXNETLWF_SYNC_SEND
179 /** Event signalled when sending to the wire is complete */
180 KEVENT EventWire;
181 /** Event signalled when NDIS returns our receive notification */
182 KEVENT EventHost;
183#else /* !VBOXNETLWF_SYNC_SEND */
184 /** Event signalled when all pending sends (both to wire and host) have completed */
185 NDIS_EVENT EventSendComplete;
186 /** Counter for pending sends (both to wire and host) */
187 int32_t cPendingBuffers;
188 /** Work Item to deliver offloading indications at passive IRQL */
189 NDIS_HANDLE hWorkItem;
190#endif /* !VBOXNETLWF_SYNC_SEND */
191 /** MAC address of underlying adapter */
192 RTMAC MacAddr;
193 /** Saved offload configuration */
194 NDIS_OFFLOAD SavedOffloadConfig;
195 /** the cloned request we have passed down */
196 PNDIS_OID_REQUEST pPendingRequest;
197 /** true if the underlying miniport supplied offloading config */
198 bool fOffloadConfigValid;
199 /** true if the trunk expects data from us */
200 bool fActive;
201 /** true if the host wants the adapter to be in promisc mode */
202 bool fHostPromisc;
203 /** Name of underlying adapter */
204 char szMiniportName[1];
205} VBOXNETLWF_MODULE;
206typedef VBOXNETLWF_MODULE *PVBOXNETLWF_MODULE;
207
208/*
209 * A structure to wrap OID requests in.
210 */
211typedef struct _VBOXNETLWF_OIDREQ {
212 NDIS_OID_REQUEST Request;
213 NDIS_STATUS Status;
214 NDIS_EVENT Event;
215} VBOXNETLWF_OIDREQ;
216typedef VBOXNETLWF_OIDREQ *PVBOXNETLWF_OIDREQ;
217
218/* Forward declarations */
219static VOID vboxNetLwfWinUnloadDriver(IN PDRIVER_OBJECT pDriver);
220static int vboxNetLwfWinInitBase();
221static int vboxNetLwfWinFini();
222
223#ifdef DEBUG
224static const char *vboxNetLwfWinStatusToText(NDIS_STATUS code)
225{
226 switch (code)
227 {
228 case NDIS_STATUS_MEDIA_CONNECT: return "NDIS_STATUS_MEDIA_CONNECT";
229 case NDIS_STATUS_MEDIA_DISCONNECT: return "NDIS_STATUS_MEDIA_DISCONNECT";
230 case NDIS_STATUS_RESET_START: return "NDIS_STATUS_RESET_START";
231 case NDIS_STATUS_RESET_END: return "NDIS_STATUS_RESET_END";
232 case NDIS_STATUS_MEDIA_BUSY: return "NDIS_STATUS_MEDIA_BUSY";
233 case NDIS_STATUS_MEDIA_SPECIFIC_INDICATION: return "NDIS_STATUS_MEDIA_SPECIFIC_INDICATION";
234 case NDIS_STATUS_LINK_SPEED_CHANGE: return "NDIS_STATUS_LINK_SPEED_CHANGE";
235 case NDIS_STATUS_LINK_STATE: return "NDIS_STATUS_LINK_STATE";
236 case NDIS_STATUS_PORT_STATE: return "NDIS_STATUS_PORT_STATE";
237 case NDIS_STATUS_OPER_STATUS: return "NDIS_STATUS_OPER_STATUS";
238 case NDIS_STATUS_NETWORK_CHANGE: return "NDIS_STATUS_NETWORK_CHANGE";
239 case NDIS_STATUS_PACKET_FILTER: return "NDIS_STATUS_PACKET_FILTER";
240 case NDIS_STATUS_TASK_OFFLOAD_CURRENT_CONFIG: return "NDIS_STATUS_TASK_OFFLOAD_CURRENT_CONFIG";
241 case NDIS_STATUS_TASK_OFFLOAD_HARDWARE_CAPABILITIES: return "NDIS_STATUS_TASK_OFFLOAD_HARDWARE_CAPABILITIES";
242 case NDIS_STATUS_OFFLOAD_ENCASPULATION_CHANGE: return "NDIS_STATUS_OFFLOAD_ENCASPULATION_CHANGE";
243 case NDIS_STATUS_TCP_CONNECTION_OFFLOAD_HARDWARE_CAPABILITIES: return "NDIS_STATUS_TCP_CONNECTION_OFFLOAD_HARDWARE_CAPABILITIES";
244 }
245 return "unknown";
246}
247
248static void vboxNetLwfWinDumpFilterTypes(ULONG uFlags)
249{
250 if (uFlags & NDIS_PACKET_TYPE_DIRECTED) Log5((" NDIS_PACKET_TYPE_DIRECTED\n"));
251 if (uFlags & NDIS_PACKET_TYPE_MULTICAST) Log5((" NDIS_PACKET_TYPE_MULTICAST\n"));
252 if (uFlags & NDIS_PACKET_TYPE_ALL_MULTICAST) Log5((" NDIS_PACKET_TYPE_ALL_MULTICAST\n"));
253 if (uFlags & NDIS_PACKET_TYPE_BROADCAST) Log5((" NDIS_PACKET_TYPE_BROADCAST\n"));
254 if (uFlags & NDIS_PACKET_TYPE_PROMISCUOUS) Log5((" NDIS_PACKET_TYPE_PROMISCUOUS\n"));
255 if (uFlags & NDIS_PACKET_TYPE_ALL_FUNCTIONAL) Log5((" NDIS_PACKET_TYPE_ALL_FUNCTIONAL\n"));
256 if (uFlags & NDIS_PACKET_TYPE_ALL_LOCAL) Log5((" NDIS_PACKET_TYPE_ALL_LOCAL\n"));
257 if (uFlags & NDIS_PACKET_TYPE_FUNCTIONAL) Log5((" NDIS_PACKET_TYPE_FUNCTIONAL\n"));
258 if (uFlags & NDIS_PACKET_TYPE_GROUP) Log5((" NDIS_PACKET_TYPE_GROUP\n"));
259 if (uFlags & NDIS_PACKET_TYPE_MAC_FRAME) Log5((" NDIS_PACKET_TYPE_MAC_FRAME\n"));
260 if (uFlags & NDIS_PACKET_TYPE_SMT) Log5((" NDIS_PACKET_TYPE_SMT\n"));
261 if (uFlags & NDIS_PACKET_TYPE_SOURCE_ROUTING) Log5((" NDIS_PACKET_TYPE_SOURCE_ROUTING\n"));
262 if (uFlags == 0) Log5((" NONE\n"));
263}
264
265DECLINLINE(void) vboxNetLwfWinDumpEncapsulation(const char *pcszText, ULONG uEncapsulation)
266{
267 if (uEncapsulation == NDIS_ENCAPSULATION_NOT_SUPPORTED)
268 Log5(("%s not supported\n", pcszText));
269 else
270 {
271 Log5(("%s", pcszText));
272 if (uEncapsulation & NDIS_ENCAPSULATION_NULL)
273 Log5((" null"));
274 if (uEncapsulation & NDIS_ENCAPSULATION_IEEE_802_3)
275 Log5((" 802.3"));
276 if (uEncapsulation & NDIS_ENCAPSULATION_IEEE_802_3_P_AND_Q)
277 Log5((" 802.3pq"));
278 if (uEncapsulation & NDIS_ENCAPSULATION_IEEE_802_3_P_AND_Q_IN_OOB)
279 Log5((" 802.3pq(oob)"));
280 if (uEncapsulation & NDIS_ENCAPSULATION_IEEE_LLC_SNAP_ROUTED)
281 Log5((" LLC"));
282 Log5(("\n"));
283 }
284}
285
286DECLINLINE(const char *) vboxNetLwfWinSetOnOffText(ULONG uOnOff)
287{
288 switch (uOnOff)
289 {
290 case NDIS_OFFLOAD_SET_NO_CHANGE: return "no change";
291 case NDIS_OFFLOAD_SET_ON: return "on";
292 case NDIS_OFFLOAD_SET_OFF: return "off";
293 }
294 return "unknown";
295}
296
297DECLINLINE(const char *) vboxNetLwfWinOnOffText(ULONG uOnOff)
298{
299 switch (uOnOff)
300 {
301 case NDIS_OFFLOAD_NOT_SUPPORTED: return "off";
302 case NDIS_OFFLOAD_SUPPORTED: return "on";
303 }
304 return "unknown";
305}
306
307DECLINLINE(const char *) vboxNetLwfWinSupportedText(ULONG uSupported)
308{
309 switch (uSupported)
310 {
311 case NDIS_OFFLOAD_NOT_SUPPORTED: return "not supported";
312 case NDIS_OFFLOAD_SUPPORTED: return "supported";
313 }
314 return "unknown";
315}
316
317static void vboxNetLwfWinDumpSetOffloadSettings(PNDIS_OFFLOAD pOffloadConfig)
318{
319 vboxNetLwfWinDumpEncapsulation(" Checksum.IPv4Transmit.Encapsulation =", pOffloadConfig->Checksum.IPv4Transmit.Encapsulation);
320 Log5((" Checksum.IPv4Transmit.IpOptionsSupported = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv4Transmit.IpOptionsSupported)));
321 Log5((" Checksum.IPv4Transmit.TcpOptionsSupported = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv4Transmit.TcpOptionsSupported)));
322 Log5((" Checksum.IPv4Transmit.TcpChecksum = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv4Transmit.TcpChecksum)));
323 Log5((" Checksum.IPv4Transmit.UdpChecksum = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv4Transmit.UdpChecksum)));
324 Log5((" Checksum.IPv4Transmit.IpChecksum = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv4Transmit.IpChecksum)));
325 vboxNetLwfWinDumpEncapsulation(" Checksum.IPv4Receive.Encapsulation =", pOffloadConfig->Checksum.IPv4Receive.Encapsulation);
326 Log5((" Checksum.IPv4Receive.IpOptionsSupported = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv4Receive.IpOptionsSupported)));
327 Log5((" Checksum.IPv4Receive.TcpOptionsSupported = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv4Receive.TcpOptionsSupported)));
328 Log5((" Checksum.IPv4Receive.TcpChecksum = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv4Receive.TcpChecksum)));
329 Log5((" Checksum.IPv4Receive.UdpChecksum = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv4Receive.UdpChecksum)));
330 Log5((" Checksum.IPv4Receive.IpChecksum = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv4Receive.IpChecksum)));
331 vboxNetLwfWinDumpEncapsulation(" Checksum.IPv6Transmit.Encapsulation =", pOffloadConfig->Checksum.IPv6Transmit.Encapsulation);
332 Log5((" Checksum.IPv6Transmit.IpExtensionHeadersSupported = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv6Transmit.IpExtensionHeadersSupported)));
333 Log5((" Checksum.IPv6Transmit.TcpOptionsSupported = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv6Transmit.TcpOptionsSupported)));
334 Log5((" Checksum.IPv6Transmit.TcpChecksum = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv6Transmit.TcpChecksum)));
335 Log5((" Checksum.IPv6Transmit.UdpChecksum = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv6Transmit.UdpChecksum)));
336 vboxNetLwfWinDumpEncapsulation(" Checksum.IPv6Receive.Encapsulation =", pOffloadConfig->Checksum.IPv6Receive.Encapsulation);
337 Log5((" Checksum.IPv6Receive.IpExtensionHeadersSupported = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv6Receive.IpExtensionHeadersSupported)));
338 Log5((" Checksum.IPv6Receive.TcpOptionsSupported = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv6Receive.TcpOptionsSupported)));
339 Log5((" Checksum.IPv6Receive.TcpChecksum = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv6Receive.TcpChecksum)));
340 Log5((" Checksum.IPv6Receive.UdpChecksum = %s\n", vboxNetLwfWinSetOnOffText(pOffloadConfig->Checksum.IPv6Receive.UdpChecksum)));
341 vboxNetLwfWinDumpEncapsulation(" LsoV1.IPv4.Encapsulation =", pOffloadConfig->LsoV1.IPv4.Encapsulation);
342 Log5((" LsoV1.IPv4.TcpOptions = %s\n", vboxNetLwfWinSupportedText(pOffloadConfig->LsoV1.IPv4.TcpOptions)));
343 Log5((" LsoV1.IPv4.IpOptions = %s\n", vboxNetLwfWinSupportedText(pOffloadConfig->LsoV1.IPv4.IpOptions)));
344 vboxNetLwfWinDumpEncapsulation(" LsoV2.IPv4.Encapsulation =", pOffloadConfig->LsoV2.IPv4.Encapsulation);
345 vboxNetLwfWinDumpEncapsulation(" LsoV2.IPv6.Encapsulation =", pOffloadConfig->LsoV2.IPv6.Encapsulation);
346 Log5((" LsoV2.IPv6.IpExtensionHeadersSupported = %s\n", vboxNetLwfWinSupportedText(pOffloadConfig->LsoV2.IPv6.IpExtensionHeadersSupported)));
347 Log5((" LsoV2.IPv6.TcpOptionsSupported = %s\n", vboxNetLwfWinSupportedText(pOffloadConfig->LsoV2.IPv6.TcpOptionsSupported)));
348}
349
350static void vboxNetLwfWinDumpOffloadSettings(PNDIS_OFFLOAD pOffloadConfig)
351{
352 vboxNetLwfWinDumpEncapsulation(" Checksum.IPv4Transmit.Encapsulation =", pOffloadConfig->Checksum.IPv4Transmit.Encapsulation);
353 Log5((" Checksum.IPv4Transmit.IpOptionsSupported = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv4Transmit.IpOptionsSupported)));
354 Log5((" Checksum.IPv4Transmit.TcpOptionsSupported = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv4Transmit.TcpOptionsSupported)));
355 Log5((" Checksum.IPv4Transmit.TcpChecksum = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv4Transmit.TcpChecksum)));
356 Log5((" Checksum.IPv4Transmit.UdpChecksum = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv4Transmit.UdpChecksum)));
357 Log5((" Checksum.IPv4Transmit.IpChecksum = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv4Transmit.IpChecksum)));
358 vboxNetLwfWinDumpEncapsulation(" Checksum.IPv4Receive.Encapsulation =", pOffloadConfig->Checksum.IPv4Receive.Encapsulation);
359 Log5((" Checksum.IPv4Receive.IpOptionsSupported = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv4Receive.IpOptionsSupported)));
360 Log5((" Checksum.IPv4Receive.TcpOptionsSupported = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv4Receive.TcpOptionsSupported)));
361 Log5((" Checksum.IPv4Receive.TcpChecksum = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv4Receive.TcpChecksum)));
362 Log5((" Checksum.IPv4Receive.UdpChecksum = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv4Receive.UdpChecksum)));
363 Log5((" Checksum.IPv4Receive.IpChecksum = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv4Receive.IpChecksum)));
364 vboxNetLwfWinDumpEncapsulation(" Checksum.IPv6Transmit.Encapsulation =", pOffloadConfig->Checksum.IPv6Transmit.Encapsulation);
365 Log5((" Checksum.IPv6Transmit.IpExtensionHeadersSupported = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv6Transmit.IpExtensionHeadersSupported)));
366 Log5((" Checksum.IPv6Transmit.TcpOptionsSupported = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv6Transmit.TcpOptionsSupported)));
367 Log5((" Checksum.IPv6Transmit.TcpChecksum = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv6Transmit.TcpChecksum)));
368 Log5((" Checksum.IPv6Transmit.UdpChecksum = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv6Transmit.UdpChecksum)));
369 vboxNetLwfWinDumpEncapsulation(" Checksum.IPv6Receive.Encapsulation =", pOffloadConfig->Checksum.IPv6Receive.Encapsulation);
370 Log5((" Checksum.IPv6Receive.IpExtensionHeadersSupported = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv6Receive.IpExtensionHeadersSupported)));
371 Log5((" Checksum.IPv6Receive.TcpOptionsSupported = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv6Receive.TcpOptionsSupported)));
372 Log5((" Checksum.IPv6Receive.TcpChecksum = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv6Receive.TcpChecksum)));
373 Log5((" Checksum.IPv6Receive.UdpChecksum = %s\n", vboxNetLwfWinOnOffText(pOffloadConfig->Checksum.IPv6Receive.UdpChecksum)));
374 vboxNetLwfWinDumpEncapsulation(" LsoV1.IPv4.Encapsulation =", pOffloadConfig->LsoV1.IPv4.Encapsulation);
375 Log5((" LsoV1.IPv4.TcpOptions = %s\n", vboxNetLwfWinSupportedText(pOffloadConfig->LsoV1.IPv4.TcpOptions)));
376 Log5((" LsoV1.IPv4.IpOptions = %s\n", vboxNetLwfWinSupportedText(pOffloadConfig->LsoV1.IPv4.IpOptions)));
377 vboxNetLwfWinDumpEncapsulation(" LsoV2.IPv4.Encapsulation =", pOffloadConfig->LsoV2.IPv4.Encapsulation);
378 vboxNetLwfWinDumpEncapsulation(" LsoV2.IPv6.Encapsulation =", pOffloadConfig->LsoV2.IPv6.Encapsulation);
379 Log5((" LsoV2.IPv6.IpExtensionHeadersSupported = %s\n", vboxNetLwfWinSupportedText(pOffloadConfig->LsoV2.IPv6.IpExtensionHeadersSupported)));
380 Log5((" LsoV2.IPv6.TcpOptionsSupported = %s\n", vboxNetLwfWinSupportedText(pOffloadConfig->LsoV2.IPv6.TcpOptionsSupported)));
381}
382
383static const char *vboxNetLwfWinStateToText(uint32_t enmState)
384{
385 switch (enmState)
386 {
387 case LwfState_Detached: return "Detached";
388 case LwfState_Attaching: return "Attaching";
389 case LwfState_Paused: return "Paused";
390 case LwfState_Restarting: return "Restarting";
391 case LwfState_Running: return "Running";
392 case LwfState_Pausing: return "Pausing";
393 }
394 return "invalid";
395}
396
397#else /* !DEBUG */
398#define vboxNetLwfWinDumpFilterTypes(uFlags)
399#define vboxNetLwfWinDumpOffloadSettings(p)
400#define vboxNetLwfWinDumpSetOffloadSettings(p)
401#endif /* DEBUG */
402
403DECLINLINE(bool) vboxNetLwfWinChangeState(PVBOXNETLWF_MODULE pModuleCtx, uint32_t enmNew, uint32_t enmOld = LwfState_32BitHack)
404{
405 AssertReturn(pModuleCtx, false);
406
407 bool fSuccess = true;
408 if (enmOld != LwfState_32BitHack)
409 {
410 fSuccess = ASMAtomicCmpXchgU32(&pModuleCtx->enmState, enmNew, enmOld);
411 if (fSuccess)
412 Log(("vboxNetLwfWinChangeState: state change %s -> %s\n",
413 vboxNetLwfWinStateToText(enmOld),
414 vboxNetLwfWinStateToText(enmNew)));
415 else
416 Log(("ERROR! vboxNetLwfWinChangeState: failed state change %s (actual=%s) -> %s\n",
417 vboxNetLwfWinStateToText(enmOld),
418 vboxNetLwfWinStateToText(ASMAtomicReadU32(&pModuleCtx->enmState)),
419 vboxNetLwfWinStateToText(enmNew)));
420 Assert(fSuccess);
421 }
422 else
423 {
424 uint32_t enmPrevState = ASMAtomicXchgU32(&pModuleCtx->enmState, enmNew);
425 Log(("vboxNetLwfWinChangeState: state change %s -> %s\n",
426 vboxNetLwfWinStateToText(enmPrevState),
427 vboxNetLwfWinStateToText(enmNew)));
428 }
429 return fSuccess;
430}
431
432DECLINLINE(void) vboxNetLwfWinInitOidRequest(PVBOXNETLWF_OIDREQ pRequest)
433{
434 NdisZeroMemory(pRequest, sizeof(VBOXNETLWF_OIDREQ));
435
436 NdisInitializeEvent(&pRequest->Event);
437
438 pRequest->Request.Header.Type = NDIS_OBJECT_TYPE_OID_REQUEST;
439 pRequest->Request.Header.Revision = NDIS_OID_REQUEST_REVISION_1;
440 pRequest->Request.Header.Size = NDIS_SIZEOF_OID_REQUEST_REVISION_1;
441
442 pRequest->Request.RequestId = (PVOID)VBOXNETLWF_REQ_ID;
443}
444
445static NDIS_STATUS vboxNetLwfWinSyncOidRequest(PVBOXNETLWF_MODULE pModuleCtx, PVBOXNETLWF_OIDREQ pRequest)
446{
447 NDIS_STATUS Status = NdisFOidRequest(pModuleCtx->hFilter, &pRequest->Request);
448 if (Status == NDIS_STATUS_PENDING)
449 {
450 NdisWaitEvent(&pRequest->Event, 0);
451 Status = pRequest->Status;
452 }
453 return Status;
454}
455
456DECLINLINE(void) vboxNetLwfWinCopyOidRequestResults(PNDIS_OID_REQUEST pFrom, PNDIS_OID_REQUEST pTo)
457{
458 switch (pFrom->RequestType)
459 {
460 case NdisRequestSetInformation:
461 pTo->DATA.SET_INFORMATION.BytesRead = pFrom->DATA.SET_INFORMATION.BytesRead;
462 pTo->DATA.SET_INFORMATION.BytesNeeded = pFrom->DATA.SET_INFORMATION.BytesNeeded;
463 break;
464 case NdisRequestMethod:
465 pTo->DATA.METHOD_INFORMATION.OutputBufferLength = pFrom->DATA.METHOD_INFORMATION.OutputBufferLength;
466 pTo->DATA.METHOD_INFORMATION.BytesWritten = pFrom->DATA.METHOD_INFORMATION.BytesWritten;
467 pTo->DATA.METHOD_INFORMATION.BytesRead = pFrom->DATA.METHOD_INFORMATION.BytesRead;
468 pTo->DATA.METHOD_INFORMATION.BytesNeeded = pFrom->DATA.METHOD_INFORMATION.BytesNeeded;
469 break;
470 case NdisRequestQueryInformation:
471 case NdisRequestQueryStatistics:
472 default:
473 pTo->DATA.QUERY_INFORMATION.BytesWritten = pFrom->DATA.QUERY_INFORMATION.BytesWritten;
474 pTo->DATA.QUERY_INFORMATION.BytesNeeded = pFrom->DATA.QUERY_INFORMATION.BytesNeeded;
475 }
476}
477
478void inline vboxNetLwfWinOverridePacketFiltersUp(PVBOXNETLWF_MODULE pModuleCtx, ULONG *pFilters)
479{
480 if (ASMAtomicReadBool(&pModuleCtx->fActive) && !ASMAtomicReadBool(&pModuleCtx->fHostPromisc))
481 *pFilters &= ~NDIS_PACKET_TYPE_PROMISCUOUS;
482}
483
484NDIS_STATUS vboxNetLwfWinOidRequest(IN NDIS_HANDLE hModuleCtx,
485 IN PNDIS_OID_REQUEST pOidRequest)
486{
487 LogFlow(("==>vboxNetLwfWinOidRequest: module=%p\n", hModuleCtx));
488 vboxNetCmnWinDumpOidRequest(__FUNCTION__, pOidRequest);
489 PVBOXNETLWF_MODULE pModuleCtx = (PVBOXNETLWF_MODULE)hModuleCtx;
490 PNDIS_OID_REQUEST pClone = NULL;
491 NDIS_STATUS Status = NdisAllocateCloneOidRequest(pModuleCtx->hFilter,
492 pOidRequest,
493 VBOXNETLWF_MEM_TAG,
494 &pClone);
495 if (Status == NDIS_STATUS_SUCCESS)
496 {
497 /* Save the pointer to the original */
498 *((PNDIS_OID_REQUEST*)(pClone->SourceReserved)) = pOidRequest;
499
500 pClone->RequestId = pOidRequest->RequestId;
501 /* We are not supposed to get another request until we are through with the one we "postponed" */
502 PNDIS_OID_REQUEST pPrev = ASMAtomicXchgPtrT(&pModuleCtx->pPendingRequest, pClone, PNDIS_OID_REQUEST);
503 Assert(pPrev == NULL);
504 pModuleCtx->pPendingRequest = pClone;
505 if (pOidRequest->RequestType == NdisRequestSetInformation
506 && pOidRequest->DATA.SET_INFORMATION.Oid == OID_GEN_CURRENT_PACKET_FILTER)
507 {
508 ASMAtomicWriteBool(&pModuleCtx->fHostPromisc, !!(*(ULONG*)pOidRequest->DATA.SET_INFORMATION.InformationBuffer & NDIS_PACKET_TYPE_PROMISCUOUS));
509 Log(("vboxNetLwfWinOidRequest: host wanted to set packet filter value to:\n"));
510 vboxNetLwfWinDumpFilterTypes(*(ULONG*)pOidRequest->DATA.SET_INFORMATION.InformationBuffer);
511 /* Keep adapter in promisc mode as long as we are active. */
512 if (ASMAtomicReadBool(&pModuleCtx->fActive))
513 *(ULONG*)pClone->DATA.SET_INFORMATION.InformationBuffer |= NDIS_PACKET_TYPE_PROMISCUOUS;
514 Log5(("vboxNetLwfWinOidRequest: pass the following packet filters to miniport:\n"));
515 vboxNetLwfWinDumpFilterTypes(*(ULONG*)pOidRequest->DATA.SET_INFORMATION.InformationBuffer);
516 }
517 if (pOidRequest->RequestType == NdisRequestSetInformation
518 && pOidRequest->DATA.SET_INFORMATION.Oid == OID_TCP_OFFLOAD_CURRENT_CONFIG)
519 {
520 Log5(("vboxNetLwfWinOidRequest: offloading set to:\n"));
521 vboxNetLwfWinDumpSetOffloadSettings((PNDIS_OFFLOAD)pOidRequest->DATA.SET_INFORMATION.InformationBuffer);
522 }
523
524 /* Forward the clone to underlying filters/miniport */
525 Status = NdisFOidRequest(pModuleCtx->hFilter, pClone);
526 if (Status != NDIS_STATUS_PENDING)
527 {
528 /* Synchronous completion */
529 pPrev = ASMAtomicXchgPtrT(&pModuleCtx->pPendingRequest, NULL, PNDIS_OID_REQUEST);
530 Assert(pPrev == pClone);
531 Log5(("vboxNetLwfWinOidRequest: got the following packet filters from miniport:\n"));
532 vboxNetLwfWinDumpFilterTypes(*(ULONG*)pOidRequest->DATA.QUERY_INFORMATION.InformationBuffer);
533 /*
534 * The host does not expect the adapter to be in promisc mode,
535 * unless it enabled the mode. Let's not disillusion it.
536 */
537 if ( pOidRequest->RequestType == NdisRequestQueryInformation
538 && pOidRequest->DATA.QUERY_INFORMATION.Oid == OID_GEN_CURRENT_PACKET_FILTER)
539 vboxNetLwfWinOverridePacketFiltersUp(pModuleCtx, (ULONG*)pOidRequest->DATA.QUERY_INFORMATION.InformationBuffer);
540 Log5(("vboxNetLwfWinOidRequest: reporting to the host the following packet filters:\n"));
541 vboxNetLwfWinDumpFilterTypes(*(ULONG*)pOidRequest->DATA.QUERY_INFORMATION.InformationBuffer);
542 vboxNetLwfWinCopyOidRequestResults(pClone, pOidRequest);
543 NdisFreeCloneOidRequest(pModuleCtx->hFilter, pClone);
544 }
545 /* In case of async completion we do the rest in vboxNetLwfWinOidRequestComplete() */
546 }
547 else
548 {
549 Log(("ERROR! vboxNetLwfWinOidRequest: NdisAllocateCloneOidRequest failed with 0x%x\n", Status));
550 }
551 LogFlow(("<==vboxNetLwfWinOidRequest: Status=0x%x\n", Status));
552 return Status;
553}
554
555VOID vboxNetLwfWinOidRequestComplete(IN NDIS_HANDLE hModuleCtx,
556 IN PNDIS_OID_REQUEST pRequest,
557 IN NDIS_STATUS Status)
558{
559 LogFlow(("==>vboxNetLwfWinOidRequestComplete: module=%p req=%p status=0x%x\n", hModuleCtx, pRequest, Status));
560 PVBOXNETLWF_MODULE pModuleCtx = (PVBOXNETLWF_MODULE)hModuleCtx;
561 PNDIS_OID_REQUEST pOriginal = *((PNDIS_OID_REQUEST*)(pRequest->SourceReserved));
562 if (pOriginal)
563 {
564 /* NDIS is supposed to serialize requests */
565 PNDIS_OID_REQUEST pPrev = ASMAtomicXchgPtrT(&pModuleCtx->pPendingRequest, NULL, PNDIS_OID_REQUEST);
566 Assert(pPrev == pRequest);
567
568 Log5(("vboxNetLwfWinOidRequestComplete: completed rq type=%d oid=%x\n", pRequest->RequestType, pRequest->DATA.QUERY_INFORMATION.Oid));
569 vboxNetLwfWinCopyOidRequestResults(pRequest, pOriginal);
570 if ( pRequest->RequestType == NdisRequestQueryInformation
571 && pRequest->DATA.QUERY_INFORMATION.Oid == OID_GEN_CURRENT_PACKET_FILTER)
572 {
573 Log5(("vboxNetLwfWinOidRequestComplete: underlying miniport reports its packet filters:\n"));
574 vboxNetLwfWinDumpFilterTypes(*(ULONG*)pRequest->DATA.QUERY_INFORMATION.InformationBuffer);
575 vboxNetLwfWinOverridePacketFiltersUp(pModuleCtx, (ULONG*)pRequest->DATA.QUERY_INFORMATION.InformationBuffer);
576 Log5(("vboxNetLwfWinOidRequestComplete: reporting the following packet filters to upper protocol:\n"));
577 vboxNetLwfWinDumpFilterTypes(*(ULONG*)pRequest->DATA.QUERY_INFORMATION.InformationBuffer);
578 }
579 NdisFreeCloneOidRequest(pModuleCtx->hFilter, pRequest);
580 NdisFOidRequestComplete(pModuleCtx->hFilter, pOriginal, Status);
581 }
582 else
583 {
584 /* This is not a clone, we originated it */
585 Log(("vboxNetLwfWinOidRequestComplete: locally originated request (%p) completed, status=0x%x\n", pRequest, Status));
586 PVBOXNETLWF_OIDREQ pRqWrapper = RT_FROM_MEMBER(pRequest, VBOXNETLWF_OIDREQ, Request);
587 pRqWrapper->Status = Status;
588 NdisSetEvent(&pRqWrapper->Event);
589 }
590 LogFlow(("<==vboxNetLwfWinOidRequestComplete\n"));
591}
592
593
594static bool vboxNetLwfWinIsPromiscuous(PVBOXNETLWF_MODULE pModuleCtx)
595{
596 return ASMAtomicReadBool(&pModuleCtx->fHostPromisc);
597}
598
599#if 0
600static NDIS_STATUS vboxNetLwfWinGetPacketFilter(PVBOXNETLWF_MODULE pModuleCtx)
601{
602 LogFlow(("==>vboxNetLwfWinGetPacketFilter: module=%p\n", pModuleCtx));
603 VBOXNETLWF_OIDREQ Rq;
604 vboxNetLwfWinInitOidRequest(&Rq);
605 Rq.Request.RequestType = NdisRequestQueryInformation;
606 Rq.Request.DATA.QUERY_INFORMATION.Oid = OID_GEN_CURRENT_PACKET_FILTER;
607 Rq.Request.DATA.QUERY_INFORMATION.InformationBuffer = &pModuleCtx->uPacketFilter;
608 Rq.Request.DATA.QUERY_INFORMATION.InformationBufferLength = sizeof(pModuleCtx->uPacketFilter);
609 NDIS_STATUS Status = vboxNetLwfWinSyncOidRequest(pModuleCtx, &Rq);
610 if (Status != NDIS_STATUS_SUCCESS)
611 {
612 Log(("ERROR! vboxNetLwfWinGetPacketFilter: vboxNetLwfWinSyncOidRequest(query, OID_GEN_CURRENT_PACKET_FILTER) failed with 0x%x\n", Status));
613 return FALSE;
614 }
615 if (Rq.Request.DATA.QUERY_INFORMATION.BytesWritten != sizeof(pModuleCtx->uPacketFilter))
616 {
617 Log(("ERROR! vboxNetLwfWinGetPacketFilter: vboxNetLwfWinSyncOidRequest(query, OID_GEN_CURRENT_PACKET_FILTER) failed to write neccessary amount (%d bytes), actually written %d bytes\n", sizeof(pModuleCtx->uPacketFilter), Rq.Request.DATA.QUERY_INFORMATION.BytesWritten));
618 }
619
620 Log5(("vboxNetLwfWinGetPacketFilter: OID_GEN_CURRENT_PACKET_FILTER query returned the following filters:\n"));
621 vboxNetLwfWinDumpFilterTypes(pModuleCtx->uPacketFilter);
622
623 LogFlow(("<==vboxNetLwfWinGetPacketFilter: status=0x%x\n", Status));
624 return Status;
625}
626#endif
627
628static NDIS_STATUS vboxNetLwfWinSetPacketFilter(PVBOXNETLWF_MODULE pModuleCtx, bool fPromisc)
629{
630 LogFlow(("==>vboxNetLwfWinSetPacketFilter: module=%p %s\n", pModuleCtx, fPromisc ? "promiscuous" : "normal"));
631 ULONG uFilter = 0;
632 VBOXNETLWF_OIDREQ Rq;
633 vboxNetLwfWinInitOidRequest(&Rq);
634 Rq.Request.RequestType = NdisRequestQueryInformation;
635 Rq.Request.DATA.QUERY_INFORMATION.Oid = OID_GEN_CURRENT_PACKET_FILTER;
636 Rq.Request.DATA.QUERY_INFORMATION.InformationBuffer = &uFilter;
637 Rq.Request.DATA.QUERY_INFORMATION.InformationBufferLength = sizeof(uFilter);
638 NDIS_STATUS Status = vboxNetLwfWinSyncOidRequest(pModuleCtx, &Rq);
639 if (Status != NDIS_STATUS_SUCCESS)
640 {
641 Log(("ERROR! vboxNetLwfWinSetPacketFilter: vboxNetLwfWinSyncOidRequest(query, OID_GEN_CURRENT_PACKET_FILTER) failed with 0x%x\n", Status));
642 return Status;
643 }
644 if (Rq.Request.DATA.QUERY_INFORMATION.BytesWritten != sizeof(uFilter))
645 {
646 Log(("ERROR! vboxNetLwfWinSetPacketFilter: vboxNetLwfWinSyncOidRequest(query, OID_GEN_CURRENT_PACKET_FILTER) failed to write neccessary amount (%d bytes), actually written %d bytes\n", sizeof(uFilter), Rq.Request.DATA.QUERY_INFORMATION.BytesWritten));
647 return NDIS_STATUS_FAILURE;
648 }
649
650 Log5(("vboxNetLwfWinSetPacketFilter: OID_GEN_CURRENT_PACKET_FILTER query returned the following filters:\n"));
651 vboxNetLwfWinDumpFilterTypes(uFilter);
652
653 if (fPromisc)
654 {
655 /* If we about to go promiscuous, save the state before we change it. */
656 ASMAtomicWriteBool(&pModuleCtx->fHostPromisc, !!(uFilter & NDIS_PACKET_TYPE_PROMISCUOUS));
657 uFilter |= NDIS_PACKET_TYPE_PROMISCUOUS;
658 }
659 else
660 {
661 /* Reset promisc only if it was not enabled before we had changed it. */
662 if (!ASMAtomicReadBool(&pModuleCtx->fHostPromisc))
663 uFilter &= ~NDIS_PACKET_TYPE_PROMISCUOUS;
664 }
665
666 Log5(("vboxNetLwfWinSetPacketFilter: OID_GEN_CURRENT_PACKET_FILTER about to set the following filters:\n"));
667 vboxNetLwfWinDumpFilterTypes(uFilter);
668
669 NdisResetEvent(&Rq.Event); /* need to reset as it has been set by query op */
670 Rq.Request.RequestType = NdisRequestSetInformation;
671 Rq.Request.DATA.SET_INFORMATION.Oid = OID_GEN_CURRENT_PACKET_FILTER;
672 Rq.Request.DATA.SET_INFORMATION.InformationBuffer = &uFilter;
673 Rq.Request.DATA.SET_INFORMATION.InformationBufferLength = sizeof(uFilter);
674 Status = vboxNetLwfWinSyncOidRequest(pModuleCtx, &Rq);
675 if (Status != NDIS_STATUS_SUCCESS)
676 {
677 Log(("ERROR! vboxNetLwfWinSetPacketFilter: vboxNetLwfWinSyncOidRequest(set, OID_GEN_CURRENT_PACKET_FILTER, vvv below vvv) failed with 0x%x\n", Status));
678 vboxNetLwfWinDumpFilterTypes(uFilter);
679 }
680 LogFlow(("<==vboxNetLwfWinSetPacketFilter: status=0x%x\n", Status));
681 return Status;
682}
683
684
685static NTSTATUS vboxNetLwfWinDevDispatch(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp)
686{
687 PIO_STACK_LOCATION pIrpSl = IoGetCurrentIrpStackLocation(pIrp);;
688 NTSTATUS Status = STATUS_SUCCESS;
689
690 switch (pIrpSl->MajorFunction)
691 {
692 case IRP_MJ_DEVICE_CONTROL:
693 Status = STATUS_NOT_SUPPORTED;
694 break;
695 case IRP_MJ_CREATE:
696 case IRP_MJ_CLEANUP:
697 case IRP_MJ_CLOSE:
698 break;
699 default:
700 Assert(0);
701 break;
702 }
703
704 pIrp->IoStatus.Status = Status;
705 IoCompleteRequest(pIrp, IO_NO_INCREMENT);
706
707 return Status;
708}
709
710/** @todo So far we had no use for device, should we even bother to create it? */
711static NDIS_STATUS vboxNetLwfWinDevCreate(PVBOXNETLWFGLOBALS pGlobals)
712{
713 NDIS_STRING DevName, LinkName;
714 PDRIVER_DISPATCH aMajorFunctions[IRP_MJ_MAXIMUM_FUNCTION+1];
715 NdisInitUnicodeString(&DevName, VBOXNETLWF_NAME_DEVICE);
716 NdisInitUnicodeString(&LinkName, VBOXNETLWF_NAME_LINK);
717
718 Assert(!pGlobals->hDevice);
719 Assert(!pGlobals->pDevObj);
720 NdisZeroMemory(aMajorFunctions, sizeof (aMajorFunctions));
721 aMajorFunctions[IRP_MJ_CREATE] = vboxNetLwfWinDevDispatch;
722 aMajorFunctions[IRP_MJ_CLEANUP] = vboxNetLwfWinDevDispatch;
723 aMajorFunctions[IRP_MJ_CLOSE] = vboxNetLwfWinDevDispatch;
724 aMajorFunctions[IRP_MJ_DEVICE_CONTROL] = vboxNetLwfWinDevDispatch;
725
726 NDIS_DEVICE_OBJECT_ATTRIBUTES DeviceAttributes;
727 NdisZeroMemory(&DeviceAttributes, sizeof(DeviceAttributes));
728 DeviceAttributes.Header.Type = NDIS_OBJECT_TYPE_DEVICE_OBJECT_ATTRIBUTES;
729 DeviceAttributes.Header.Revision = NDIS_DEVICE_OBJECT_ATTRIBUTES_REVISION_1;
730 DeviceAttributes.Header.Size = sizeof(DeviceAttributes);
731 DeviceAttributes.DeviceName = &DevName;
732 DeviceAttributes.SymbolicName = &LinkName;
733 DeviceAttributes.MajorFunctions = aMajorFunctions;
734 //DeviceAttributes.ExtensionSize = sizeof(FILTER_DEVICE_EXTENSION);
735
736 NDIS_STATUS Status = NdisRegisterDeviceEx(pGlobals->hFilterDriver,
737 &DeviceAttributes,
738 &pGlobals->pDevObj,
739 &pGlobals->hDevice);
740 Log(("vboxNetLwfWinDevCreate: NdisRegisterDeviceEx returned 0x%x\n", Status));
741 Assert(Status == NDIS_STATUS_SUCCESS);
742#if 0
743 if (Status == NDIS_STATUS_SUCCESS)
744 {
745 PFILTER_DEVICE_EXTENSION pExtension;
746 pExtension = NdisGetDeviceReservedExtension(pGlobals->pDevObj);
747 pExtension->Signature = VBOXNETLWF_MEM_TAG;
748 pExtension->Handle = pGlobals->hFilterDriver;
749 }
750#endif
751 return Status;
752}
753
754static void vboxNetLwfWinDevDestroy(PVBOXNETLWFGLOBALS pGlobals)
755{
756 Assert(pGlobals->hDevice);
757 Assert(pGlobals->pDevObj);
758 NdisDeregisterDeviceEx(pGlobals->hDevice);
759 pGlobals->hDevice = NULL;
760 pGlobals->pDevObj = NULL;
761}
762
763static void vboxNetLwfWinUpdateSavedOffloadConfig(PVBOXNETLWF_MODULE pModuleCtx, PNDIS_OFFLOAD pOffload)
764{
765 pModuleCtx->SavedOffloadConfig = *pOffload;
766 pModuleCtx->fOffloadConfigValid = true;
767}
768
769static NDIS_STATUS vboxNetLwfWinAttach(IN NDIS_HANDLE hFilter, IN NDIS_HANDLE hDriverCtx,
770 IN PNDIS_FILTER_ATTACH_PARAMETERS pParameters)
771{
772 LogFlow(("==>vboxNetLwfWinAttach: filter=%p\n", hFilter));
773
774 PVBOXNETLWFGLOBALS pGlobals = (PVBOXNETLWFGLOBALS)hDriverCtx;
775 AssertReturn(pGlobals, NDIS_STATUS_FAILURE);
776
777 ANSI_STRING strMiniportName;
778 /* We use the miniport name to associate this filter module with the netflt instance */
779 NTSTATUS rc = RtlUnicodeStringToAnsiString(&strMiniportName,
780 pParameters->BaseMiniportName,
781 TRUE);
782 if (rc != STATUS_SUCCESS)
783 {
784 Log(("ERROR! vboxNetLwfWinAttach: RtlUnicodeStringToAnsiString(%ls) failed with 0x%x\n",
785 pParameters->BaseMiniportName, rc));
786 return NDIS_STATUS_FAILURE;
787 }
788 DbgPrint("vboxNetLwfWinAttach: friendly name=%wZ\n", pParameters->BaseMiniportInstanceName);
789 DbgPrint("vboxNetLwfWinAttach: name=%Z\n", strMiniportName);
790
791 UINT cbModuleWithNameExtra = sizeof(VBOXNETLWF_MODULE) + strMiniportName.Length;
792 PVBOXNETLWF_MODULE pModuleCtx = (PVBOXNETLWF_MODULE)NdisAllocateMemoryWithTagPriority(hFilter,
793 cbModuleWithNameExtra,
794 VBOXNETLWF_MEM_TAG,
795 LowPoolPriority);
796 if (!pModuleCtx)
797 {
798 RtlFreeAnsiString(&strMiniportName);
799 return NDIS_STATUS_RESOURCES;
800 }
801 Log4(("vboxNetLwfWinAttach: allocated module context 0x%p\n", pModuleCtx));
802
803 NdisZeroMemory(pModuleCtx, cbModuleWithNameExtra);
804 NdisMoveMemory(pModuleCtx->szMiniportName, strMiniportName.Buffer, strMiniportName.Length);
805 RtlFreeAnsiString(&strMiniportName);
806
807 pModuleCtx->hWorkItem = NdisAllocateIoWorkItem(g_VBoxNetLwfGlobals.hFilterDriver);
808 if (!pModuleCtx->hWorkItem)
809 {
810 Log(("ERROR! vboxNetLwfWinAttach: Failed to allocate work item for %ls\n",
811 pParameters->BaseMiniportName));
812 NdisFreeMemory(pModuleCtx, 0, 0);
813 return NDIS_STATUS_RESOURCES;
814 }
815
816 Assert(pParameters->MacAddressLength == sizeof(RTMAC));
817 NdisMoveMemory(&pModuleCtx->MacAddr, pParameters->CurrentMacAddress, RT_MIN(sizeof(RTMAC), pParameters->MacAddressLength));
818 if (pParameters->DefaultOffloadConfiguration)
819 vboxNetLwfWinUpdateSavedOffloadConfig(pModuleCtx, pParameters->DefaultOffloadConfiguration);
820
821 pModuleCtx->pGlobals = pGlobals;
822 pModuleCtx->hFilter = hFilter;
823 vboxNetLwfWinChangeState(pModuleCtx, LwfState_Attaching);
824 /* Initialize transmission mutex and events */
825 NDIS_INIT_MUTEX(&pModuleCtx->InTransmit);
826#ifdef VBOXNETLWF_SYNC_SEND
827 KeInitializeEvent(&pModuleCtx->EventWire, SynchronizationEvent, FALSE);
828 KeInitializeEvent(&pModuleCtx->EventHost, SynchronizationEvent, FALSE);
829#else /* !VBOXNETLWF_SYNC_SEND */
830 NdisInitializeEvent(&pModuleCtx->EventSendComplete);
831 pModuleCtx->cPendingBuffers = 0;
832#endif /* !VBOXNETLWF_SYNC_SEND */
833 /* Allocate buffer pools */
834 NET_BUFFER_LIST_POOL_PARAMETERS PoolParams;
835 NdisZeroMemory(&PoolParams, sizeof(PoolParams));
836 PoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT;
837 PoolParams.Header.Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1;
838 PoolParams.Header.Size = sizeof(PoolParams);
839 PoolParams.ProtocolId = NDIS_PROTOCOL_ID_DEFAULT;
840 PoolParams.fAllocateNetBuffer = TRUE;
841 PoolParams.ContextSize = 0; /** @todo Do we need to consider underlying drivers? I think not. */
842 PoolParams.PoolTag = VBOXNETLWF_MEM_TAG;
843#ifndef VBOXNETLWF_SYNC_SEND
844 PoolParams.DataSize = 2048; /** @todo figure out the optimal size, use several pools if necessary, make configurable, etc */
845#endif /* !VBOXNETLWF_SYNC_SEND */
846
847 pModuleCtx->hPool = NdisAllocateNetBufferListPool(hFilter, &PoolParams);
848 if (!pModuleCtx->hPool)
849 {
850 Log(("ERROR! vboxNetLwfWinAttach: NdisAllocateNetBufferListPool failed\n"));
851 NdisFreeIoWorkItem(pModuleCtx->hWorkItem);
852 NdisFreeMemory(pModuleCtx, 0, 0);
853 return NDIS_STATUS_RESOURCES;
854 }
855 Log4(("vboxNetLwfWinAttach: allocated NBL+NB pool 0x%p\n", pModuleCtx->hPool));
856
857 NDIS_FILTER_ATTRIBUTES Attributes;
858 NdisZeroMemory(&Attributes, sizeof(Attributes));
859 Attributes.Header.Revision = NDIS_FILTER_ATTRIBUTES_REVISION_1;
860 Attributes.Header.Size = sizeof(Attributes);
861 Attributes.Header.Type = NDIS_OBJECT_TYPE_FILTER_ATTRIBUTES;
862 Attributes.Flags = 0;
863 NDIS_STATUS Status = NdisFSetAttributes(hFilter, pModuleCtx, &Attributes);
864 if (Status != NDIS_STATUS_SUCCESS)
865 {
866 Log(("ERROR! vboxNetLwfWinAttach: NdisFSetAttributes failed with 0x%x\n", Status));
867 NdisFreeNetBufferListPool(pModuleCtx->hPool);
868 Log4(("vboxNetLwfWinAttach: freed NBL+NB pool 0x%p\n", pModuleCtx->hPool));
869 NdisFreeIoWorkItem(pModuleCtx->hWorkItem);
870 NdisFreeMemory(pModuleCtx, 0, 0);
871 return NDIS_STATUS_RESOURCES;
872 }
873 /* Insert into module chain */
874 NdisAcquireSpinLock(&pGlobals->Lock);
875 RTListPrepend(&pGlobals->listModules, &pModuleCtx->node);
876 NdisReleaseSpinLock(&pGlobals->Lock);
877
878 vboxNetLwfWinChangeState(pModuleCtx, LwfState_Paused);
879
880 /// @todo Somehow the packet filter is 0 at this point: Status = vboxNetLwfWinGetPacketFilter(pModuleCtx);
881 /// @todo We actually update it later in status handler, perhaps we should not do anything here.
882
883 LogFlow(("<==vboxNetLwfWinAttach: Status = 0x%x\n", Status));
884 return Status;
885}
886
887static VOID vboxNetLwfWinDetach(IN NDIS_HANDLE hModuleCtx)
888{
889 LogFlow(("==>vboxNetLwfWinDetach: module=%p\n", hModuleCtx));
890 PVBOXNETLWF_MODULE pModuleCtx = (PVBOXNETLWF_MODULE)hModuleCtx;
891 vboxNetLwfWinChangeState(pModuleCtx, LwfState_Detached, LwfState_Paused);
892
893 /* Remove from module chain */
894 NdisAcquireSpinLock(&pModuleCtx->pGlobals->Lock);
895 RTListNodeRemove(&pModuleCtx->node);
896 NdisReleaseSpinLock(&pModuleCtx->pGlobals->Lock);
897
898 PVBOXNETFLTINS pNetFltIns = pModuleCtx->pNetFlt; /// @todo Atomic?
899 if (pNetFltIns && vboxNetFltTryRetainBusyNotDisconnected(pNetFltIns))
900 {
901 /*
902 * Set hModuleCtx to null now in order to prevent filter restart,
903 * OID requests and other stuff associated with NetFlt deactivation.
904 */
905 pNetFltIns->u.s.WinIf.hModuleCtx = NULL;
906 /* Notify NetFlt that we are going down */
907 pNetFltIns->pSwitchPort->pfnDisconnect(pNetFltIns->pSwitchPort, &pNetFltIns->MyPort, vboxNetFltPortReleaseBusy);
908 /* We do not 'release' netflt instance since it has been done by pfnDisconnect */
909 }
910 pModuleCtx->pNetFlt = NULL;
911
912 /*
913 * We have to make sure that all NET_BUFFER_LIST structures have been freed by now, but
914 * it does not require us to do anything here since it has already been taken care of
915 * by vboxNetLwfWinPause().
916 */
917 if (pModuleCtx->hPool)
918 {
919 NdisFreeNetBufferListPool(pModuleCtx->hPool);
920 Log4(("vboxNetLwfWinDetach: freed NBL+NB pool 0x%p\n", pModuleCtx->hPool));
921 }
922 NdisFreeIoWorkItem(pModuleCtx->hWorkItem);
923 NdisFreeMemory(hModuleCtx, 0, 0);
924 Log4(("vboxNetLwfWinDetach: freed module context 0x%p\n", pModuleCtx));
925 LogFlow(("<==vboxNetLwfWinDetach\n"));
926}
927
928
929static NDIS_STATUS vboxNetLwfWinPause(IN NDIS_HANDLE hModuleCtx, IN PNDIS_FILTER_PAUSE_PARAMETERS pParameters)
930{
931 LogFlow(("==>vboxNetLwfWinPause: module=%p\n", hModuleCtx));
932 PVBOXNETLWF_MODULE pModuleCtx = (PVBOXNETLWF_MODULE)hModuleCtx;
933 vboxNetLwfWinChangeState(pModuleCtx, LwfState_Pausing, LwfState_Running);
934 /* Wait for pending send/indication operations to complete. */
935 NDIS_WAIT_FOR_MUTEX(&pModuleCtx->InTransmit);
936#ifndef VBOXNETLWF_SYNC_SEND
937 NdisWaitEvent(&pModuleCtx->EventSendComplete, 1000 /* ms */);
938#endif /* !VBOXNETLWF_SYNC_SEND */
939 vboxNetLwfWinChangeState(pModuleCtx, LwfState_Paused, LwfState_Pausing);
940 NDIS_RELEASE_MUTEX(&pModuleCtx->InTransmit);
941 LogFlow(("<==vboxNetLwfWinPause\n"));
942 return NDIS_STATUS_SUCCESS; /* Failure is not an option */
943}
944
945
946static void vboxNetLwfWinIndicateOffload(PVBOXNETLWF_MODULE pModuleCtx, PNDIS_OFFLOAD pOffload)
947{
948 Log5(("vboxNetLwfWinIndicateOffload: offload config changed to:\n"));
949 vboxNetLwfWinDumpOffloadSettings(pOffload);
950 NDIS_STATUS_INDICATION OffloadingIndication;
951 NdisZeroMemory(&OffloadingIndication, sizeof(OffloadingIndication));
952 OffloadingIndication.Header.Type = NDIS_OBJECT_TYPE_STATUS_INDICATION;
953 OffloadingIndication.Header.Revision = NDIS_STATUS_INDICATION_REVISION_1;
954 OffloadingIndication.Header.Size = NDIS_SIZEOF_STATUS_INDICATION_REVISION_1;
955 OffloadingIndication.SourceHandle = pModuleCtx->hFilter;
956 OffloadingIndication.StatusCode = NDIS_STATUS_TASK_OFFLOAD_CURRENT_CONFIG;
957 OffloadingIndication.StatusBuffer = pOffload;
958 OffloadingIndication.StatusBufferSize = sizeof(NDIS_OFFLOAD);
959 NdisFIndicateStatus(pModuleCtx->hFilter, &OffloadingIndication);
960}
961
962
963static NDIS_STATUS vboxNetLwfWinRestart(IN NDIS_HANDLE hModuleCtx, IN PNDIS_FILTER_RESTART_PARAMETERS pParameters)
964{
965 LogFlow(("==>vboxNetLwfWinRestart: module=%p\n", hModuleCtx));
966 PVBOXNETLWF_MODULE pModuleCtx = (PVBOXNETLWF_MODULE)hModuleCtx;
967 vboxNetLwfWinChangeState(pModuleCtx, LwfState_Restarting, LwfState_Paused);
968
969 vboxNetLwfWinChangeState(pModuleCtx, LwfState_Running, LwfState_Restarting);
970 NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
971 LogFlow(("<==vboxNetLwfWinRestart: Status = 0x%x\n", Status));
972 return Status;
973}
974
975
976static void vboxNetLwfWinDumpPackets(const char *pszMsg, PNET_BUFFER_LIST pBufLists)
977{
978 for (PNET_BUFFER_LIST pList = pBufLists; pList; pList = NET_BUFFER_LIST_NEXT_NBL(pList))
979 {
980 for (PNET_BUFFER pBuf = NET_BUFFER_LIST_FIRST_NB(pList); pBuf; pBuf = NET_BUFFER_NEXT_NB(pBuf))
981 {
982 Log(("%s packet: cb=%d\n", pszMsg, NET_BUFFER_DATA_LENGTH(pBuf)));
983 }
984 }
985}
986
987DECLINLINE(const char *) vboxNetLwfWinEthTypeStr(uint16_t uType)
988{
989 switch (uType)
990 {
991 case RTNET_ETHERTYPE_IPV4: return "IP";
992 case RTNET_ETHERTYPE_IPV6: return "IPv6";
993 case RTNET_ETHERTYPE_ARP: return "ARP";
994 }
995 return "unknown";
996}
997
998#define VBOXNETLWF_PKTDMPSIZE 0x50
999
1000/**
1001 * Dump a packet to debug log.
1002 *
1003 * @param cpPacket The packet.
1004 * @param cb The size of the packet.
1005 * @param cszText A string denoting direction of packet transfer.
1006 */
1007DECLINLINE(void) vboxNetLwfWinDumpPacket(PCINTNETSG pSG, const char *cszText)
1008{
1009 uint8_t bPacket[VBOXNETLWF_PKTDMPSIZE];
1010
1011 uint32_t cb = pSG->cbTotal < VBOXNETLWF_PKTDMPSIZE ? pSG->cbTotal : VBOXNETLWF_PKTDMPSIZE;
1012 IntNetSgReadEx(pSG, 0, cb, bPacket);
1013
1014 AssertReturnVoid(cb >= 14);
1015
1016 uint8_t *pHdr = bPacket;
1017 uint8_t *pEnd = bPacket + cb;
1018 AssertReturnVoid(pEnd - pHdr >= 14);
1019 uint16_t uEthType = RT_N2H_U16(*(uint16_t*)(pHdr+12));
1020 Log2(("NetLWF: %s (%d bytes), %RTmac => %RTmac, EthType=%s(0x%x)\n",
1021 cszText, cb, pHdr+6, pHdr, vboxNetLwfWinEthTypeStr(uEthType), uEthType));
1022 pHdr += sizeof(RTNETETHERHDR);
1023 if (uEthType == RTNET_ETHERTYPE_VLAN)
1024 {
1025 AssertReturnVoid(pEnd - pHdr >= 4);
1026 uEthType = RT_N2H_U16(*(uint16_t*)(pHdr+2));
1027 Log2((" + VLAN: id=%d EthType=%s(0x%x)\n", RT_N2H_U16(*(uint16_t*)(pHdr)) & 0xFFF,
1028 vboxNetLwfWinEthTypeStr(uEthType), uEthType));
1029 pHdr += 2 * sizeof(uint16_t);
1030 }
1031 uint8_t uProto = 0xFF;
1032 switch (uEthType)
1033 {
1034 case RTNET_ETHERTYPE_IPV6:
1035 AssertReturnVoid(pEnd - pHdr >= 40);
1036 uProto = pHdr[6];
1037 Log2((" + IPv6: %RTnaipv6 => %RTnaipv6\n", pHdr+8, pHdr+24));
1038 pHdr += 40;
1039 break;
1040 case RTNET_ETHERTYPE_IPV4:
1041 AssertReturnVoid(pEnd - pHdr >= 20);
1042 uProto = pHdr[9];
1043 Log2((" + IP: %RTnaipv4 => %RTnaipv4\n", *(uint32_t*)(pHdr+12), *(uint32_t*)(pHdr+16)));
1044 pHdr += (pHdr[0] & 0xF) * 4;
1045 break;
1046 case RTNET_ETHERTYPE_ARP:
1047 AssertReturnVoid(pEnd - pHdr >= 28);
1048 AssertReturnVoid(RT_N2H_U16(*(uint16_t*)(pHdr+2)) == RTNET_ETHERTYPE_IPV4);
1049 switch (RT_N2H_U16(*(uint16_t*)(pHdr+6)))
1050 {
1051 case 1: /* ARP request */
1052 Log2((" + ARP-REQ: who-has %RTnaipv4 tell %RTnaipv4\n",
1053 *(uint32_t*)(pHdr+24), *(uint32_t*)(pHdr+14)));
1054 break;
1055 case 2: /* ARP reply */
1056 Log2((" + ARP-RPL: %RTnaipv4 is-at %RTmac\n",
1057 *(uint32_t*)(pHdr+14), pHdr+8));
1058 break;
1059 default:
1060 Log2((" + ARP: unknown op %d\n", RT_N2H_U16(*(uint16_t*)(pHdr+6))));
1061 break;
1062 }
1063 break;
1064 /* There is no default case as uProto is initialized with 0xFF */
1065 }
1066 while (uProto != 0xFF)
1067 {
1068 switch (uProto)
1069 {
1070 case 0: /* IPv6 Hop-by-Hop option*/
1071 case 60: /* IPv6 Destination option*/
1072 case 43: /* IPv6 Routing option */
1073 case 44: /* IPv6 Fragment option */
1074 Log2((" + IPv6 option (%d): <not implemented>\n", uProto));
1075 uProto = pHdr[0];
1076 pHdr += pHdr[1] * 8 + 8; /* Skip to the next extension/protocol */
1077 break;
1078 case 51: /* IPv6 IPsec AH */
1079 Log2((" + IPv6 IPsec AH: <not implemented>\n"));
1080 uProto = pHdr[0];
1081 pHdr += (pHdr[1] + 2) * 4; /* Skip to the next extension/protocol */
1082 break;
1083 case 50: /* IPv6 IPsec ESP */
1084 /* Cannot decode IPsec, fall through */
1085 Log2((" + IPv6 IPsec ESP: <not implemented>\n"));
1086 uProto = 0xFF;
1087 break;
1088 case 59: /* No Next Header */
1089 Log2((" + IPv6 No Next Header\n"));
1090 uProto = 0xFF;
1091 break;
1092 case 58: /* IPv6-ICMP */
1093 switch (pHdr[0])
1094 {
1095 case 1: Log2((" + IPv6-ICMP: destination unreachable, code %d\n", pHdr[1])); break;
1096 case 128: Log2((" + IPv6-ICMP: echo request\n")); break;
1097 case 129: Log2((" + IPv6-ICMP: echo reply\n")); break;
1098 default: Log2((" + IPv6-ICMP: unknown type %d, code %d\n", pHdr[0], pHdr[1])); break;
1099 }
1100 uProto = 0xFF;
1101 break;
1102 case 1: /* ICMP */
1103 switch (pHdr[0])
1104 {
1105 case 0: Log2((" + ICMP: echo reply\n")); break;
1106 case 8: Log2((" + ICMP: echo request\n")); break;
1107 case 3: Log2((" + ICMP: destination unreachable, code %d\n", pHdr[1])); break;
1108 default: Log2((" + ICMP: unknown type %d, code %d\n", pHdr[0], pHdr[1])); break;
1109 }
1110 uProto = 0xFF;
1111 break;
1112 case 6: /* TCP */
1113 Log2((" + TCP: src=%d dst=%d seq=%x ack=%x\n",
1114 RT_N2H_U16(*(uint16_t*)(pHdr)), RT_N2H_U16(*(uint16_t*)(pHdr+2)),
1115 RT_N2H_U32(*(uint32_t*)(pHdr+4)), RT_N2H_U32(*(uint32_t*)(pHdr+8))));
1116 uProto = 0xFF;
1117 break;
1118 case 17: /* UDP */
1119 Log2((" + UDP: src=%d dst=%d\n",
1120 RT_N2H_U16(*(uint16_t*)(pHdr)), RT_N2H_U16(*(uint16_t*)(pHdr+2))));
1121 uProto = 0xFF;
1122 break;
1123 default:
1124 Log2((" + Unknown: proto=0x%x\n", uProto));
1125 uProto = 0xFF;
1126 break;
1127 }
1128 }
1129 Log3(("%.*Rhxd\n", cb, bPacket));
1130}
1131
1132static void vboxNetLwfWinDestroySG(PINTNETSG pSG)
1133{
1134 NdisFreeMemory(pSG, 0, 0);
1135 Log4(("vboxNetLwfWinDestroySG: freed SG 0x%p\n", pSG));
1136}
1137
1138DECLINLINE(ULONG) vboxNetLwfWinCalcSegments(PNET_BUFFER pNetBuf)
1139{
1140 ULONG cSegs = 0;
1141 for (PMDL pMdl = NET_BUFFER_CURRENT_MDL(pNetBuf); pMdl; pMdl = NDIS_MDL_LINKAGE(pMdl))
1142 cSegs++;
1143 return cSegs;
1144}
1145
1146DECLINLINE(void) vboxNetLwfWinFreeMdlChain(PMDL pMdl)
1147{
1148#ifdef VBOXNETLWF_SYNC_SEND
1149 PMDL pMdlNext;
1150 while (pMdl)
1151 {
1152 pMdlNext = pMdl->Next;
1153 NdisFreeMdl(pMdl);
1154 Log4(("vboxNetLwfWinFreeMdlChain: freed MDL 0x%p\n", pMdl));
1155 pMdl = pMdlNext;
1156 }
1157#endif /* VBOXNETLWF_SYNC_SEND */
1158}
1159
1160/** @todo
1161 * 1) Copy data from SG to MDL (if we decide to complete asynchronously).
1162 * 2) Provide context/backfill space. Nobody does it, should we?
1163 * 3) We always get a single segment from intnet. Simplify?
1164 */
1165static PNET_BUFFER_LIST vboxNetLwfWinSGtoNB(PVBOXNETLWF_MODULE pModule, PINTNETSG pSG)
1166{
1167 AssertReturn(pSG->cSegsUsed >= 1, NULL);
1168 LogFlow(("==>vboxNetLwfWinSGtoNB: segments=%d\n", pSG->cSegsUsed));
1169
1170#ifdef VBOXNETLWF_SYNC_SEND
1171 PINTNETSEG pSeg = pSG->aSegs;
1172 PMDL pMdl = NdisAllocateMdl(pModule->hFilter, pSeg->pv, pSeg->cb);
1173 if (!pMdl)
1174 {
1175 Log(("ERROR! vboxNetLwfWinSGtoNB: failed to allocate an MDL\n"));
1176 LogFlow(("<==vboxNetLwfWinSGtoNB: return NULL\n"));
1177 return NULL;
1178 }
1179 Log4(("vboxNetLwfWinSGtoNB: allocated Mdl 0x%p\n", pMdl));
1180 PMDL pMdlCurr = pMdl;
1181 for (int i = 1; i < pSG->cSegsUsed; i++)
1182 {
1183 pSeg = &pSG->aSegs[i];
1184 pMdlCurr->Next = NdisAllocateMdl(pModule->hFilter, pSeg->pv, pSeg->cb);
1185 if (!pMdlCurr->Next)
1186 {
1187 Log(("ERROR! vboxNetLwfWinSGtoNB: failed to allocate an MDL\n"));
1188 /* Tear down all MDL we chained so far */
1189 vboxNetLwfWinFreeMdlChain(pMdl);
1190 return NULL;
1191 }
1192 pMdlCurr = pMdlCurr->Next;
1193 Log4(("vboxNetLwfWinSGtoNB: allocated Mdl 0x%p\n", pMdlCurr));
1194 }
1195 PNET_BUFFER_LIST pBufList = NdisAllocateNetBufferAndNetBufferList(pModule->hPool,
1196 0 /* ContextSize */,
1197 0 /* ContextBackFill */,
1198 pMdl,
1199 0 /* DataOffset */,
1200 pSG->cbTotal);
1201 if (pBufList)
1202 {
1203 Log4(("vboxNetLwfWinSGtoNB: allocated NBL+NB 0x%p\n", pBufList));
1204 pBufList->SourceHandle = pModule->hFilter;
1205 /** @todo Do we need to initialize anything else? */
1206 }
1207 else
1208 {
1209 Log(("ERROR! vboxNetLwfWinSGtoNB: failed to allocate an NBL+NB\n"));
1210 vboxNetLwfWinFreeMdlChain(pMdl);
1211 }
1212#else /* !VBOXNETLWF_SYNC_SEND */
1213 AssertReturn(pSG->cbTotal < 2048, NULL);
1214 PNET_BUFFER_LIST pBufList = NdisAllocateNetBufferList(pModule->hPool,
1215 0 /** @todo ContextSize */,
1216 0 /** @todo ContextBackFill */);
1217 NET_BUFFER_LIST_NEXT_NBL(pBufList) = NULL; /** @todo Is it even needed? */
1218 NET_BUFFER *pBuffer = NET_BUFFER_LIST_FIRST_NB(pBufList);
1219 NDIS_STATUS Status = NdisRetreatNetBufferDataStart(pBuffer, pSG->cbTotal, 0 /** @todo DataBackfill */, NULL);
1220 if (Status == NDIS_STATUS_SUCCESS)
1221 {
1222 uint8_t *pDst = (uint8_t*)NdisGetDataBuffer(pBuffer, pSG->cbTotal, NULL, 1, 0);
1223 if (pDst)
1224 {
1225 for (int i = 0; i < pSG->cSegsUsed; i++)
1226 {
1227 NdisMoveMemory(pDst, pSG->aSegs[i].pv, pSG->aSegs[i].cb);
1228 pDst += pSG->aSegs[i].cb;
1229 }
1230 Log4(("vboxNetLwfWinSGtoNB: allocated NBL+NB+MDL+Data 0x%p\n", pBufList));
1231 pBufList->SourceHandle = pModule->hFilter;
1232 /** @todo Do we need to initialize anything else? */
1233 }
1234 else
1235 {
1236 Log(("ERROR! vboxNetLwfWinSGtoNB: failed to obtain the buffer pointer (size=%u)\n", pSG->cbTotal));
1237 NdisAdvanceNetBufferDataStart(pBuffer, pSG->cbTotal, false, NULL); /** @todo why bother? */
1238 NdisFreeNetBufferList(pBufList);
1239 pBufList = NULL;
1240 }
1241 }
1242 else
1243 {
1244 Log(("ERROR! vboxNetLwfWinSGtoNB: NdisRetreatNetBufferDataStart failed with 0x%x (size=%u)\n", Status, pSG->cbTotal));
1245 NdisFreeNetBufferList(pBufList);
1246 pBufList = NULL;
1247 }
1248#endif /* !VBOXNETLWF_SYNC_SEND */
1249 LogFlow(("<==vboxNetLwfWinSGtoNB: return %p\n", pBufList));
1250 return pBufList;
1251}
1252
1253static PINTNETSG vboxNetLwfWinNBtoSG(PVBOXNETLWF_MODULE pModule, PNET_BUFFER pNetBuf)
1254{
1255 ULONG cbPacket = NET_BUFFER_DATA_LENGTH(pNetBuf);
1256 UINT cSegs = vboxNetLwfWinCalcSegments(pNetBuf);
1257 /* Allocate and initialize SG */
1258 PINTNETSG pSG = (PINTNETSG)NdisAllocateMemoryWithTagPriority(pModule->hFilter,
1259 RT_OFFSETOF(INTNETSG, aSegs[cSegs]),
1260 VBOXNETLWF_MEM_TAG,
1261 NormalPoolPriority);
1262 AssertReturn(pSG, pSG);
1263 Log4(("vboxNetLwfWinNBtoSG: allocated SG 0x%p\n", pSG));
1264 IntNetSgInitTempSegs(pSG, cbPacket /*cbTotal*/, cSegs, cSegs /*cSegsUsed*/);
1265
1266 int rc = NDIS_STATUS_SUCCESS;
1267 ULONG uOffset = NET_BUFFER_CURRENT_MDL_OFFSET(pNetBuf);
1268 cSegs = 0;
1269 for (PMDL pMdl = NET_BUFFER_CURRENT_MDL(pNetBuf);
1270 pMdl != NULL && cbPacket > 0;
1271 pMdl = NDIS_MDL_LINKAGE(pMdl))
1272 {
1273 PUCHAR pSrc = (PUCHAR)MmGetSystemAddressForMdlSafe(pMdl, LowPagePriority);
1274 if (!pSrc)
1275 {
1276 rc = NDIS_STATUS_RESOURCES;
1277 break;
1278 }
1279 ULONG cbSrc = MmGetMdlByteCount(pMdl);
1280 if (uOffset)
1281 {
1282 Assert(uOffset < cbSrc);
1283 pSrc += uOffset;
1284 cbSrc -= uOffset;
1285 uOffset = 0;
1286 }
1287
1288 if (cbSrc > cbPacket)
1289 cbSrc = cbPacket;
1290
1291 pSG->aSegs[cSegs].pv = pSrc;
1292 pSG->aSegs[cSegs].cb = cbSrc;
1293 pSG->aSegs[cSegs].Phys = NIL_RTHCPHYS;
1294 cSegs++;
1295 cbPacket -= cbSrc;
1296 }
1297
1298 Assert(cSegs <= pSG->cSegsAlloc);
1299
1300 if (RT_FAILURE(rc))
1301 {
1302 vboxNetLwfWinDestroySG(pSG);
1303 pSG = NULL;
1304 }
1305 else
1306 {
1307 Assert(cbPacket == 0);
1308 Assert(pSG->cSegsUsed == cSegs);
1309 }
1310 return pSG;
1311}
1312
1313static void vboxNetLwfWinDisableOffloading(PNDIS_OFFLOAD pOffloadConfig)
1314{
1315 pOffloadConfig->Checksum.IPv4Transmit.Encapsulation = NDIS_ENCAPSULATION_NOT_SUPPORTED;
1316 pOffloadConfig->Checksum.IPv4Transmit.IpOptionsSupported = NDIS_OFFLOAD_NOT_SUPPORTED;
1317 pOffloadConfig->Checksum.IPv4Transmit.TcpOptionsSupported = NDIS_OFFLOAD_NOT_SUPPORTED;
1318 pOffloadConfig->Checksum.IPv4Transmit.TcpChecksum = NDIS_OFFLOAD_NOT_SUPPORTED;
1319 pOffloadConfig->Checksum.IPv4Transmit.UdpChecksum = NDIS_OFFLOAD_NOT_SUPPORTED;
1320 pOffloadConfig->Checksum.IPv4Transmit.IpChecksum = NDIS_OFFLOAD_NOT_SUPPORTED;
1321 pOffloadConfig->Checksum.IPv6Transmit.Encapsulation = NDIS_ENCAPSULATION_NOT_SUPPORTED;
1322 pOffloadConfig->Checksum.IPv6Transmit.IpExtensionHeadersSupported = NDIS_OFFLOAD_NOT_SUPPORTED;
1323 pOffloadConfig->Checksum.IPv6Transmit.TcpOptionsSupported = NDIS_OFFLOAD_NOT_SUPPORTED;
1324 pOffloadConfig->Checksum.IPv6Transmit.TcpChecksum = NDIS_OFFLOAD_NOT_SUPPORTED;
1325 pOffloadConfig->Checksum.IPv6Transmit.UdpChecksum = NDIS_OFFLOAD_NOT_SUPPORTED;
1326 pOffloadConfig->LsoV1.IPv4.Encapsulation = NDIS_ENCAPSULATION_NOT_SUPPORTED;
1327 pOffloadConfig->LsoV1.IPv4.TcpOptions = NDIS_OFFLOAD_NOT_SUPPORTED;
1328 pOffloadConfig->LsoV1.IPv4.IpOptions = NDIS_OFFLOAD_NOT_SUPPORTED;
1329 pOffloadConfig->LsoV2.IPv4.Encapsulation = NDIS_ENCAPSULATION_NOT_SUPPORTED;
1330 pOffloadConfig->LsoV2.IPv6.Encapsulation = NDIS_ENCAPSULATION_NOT_SUPPORTED;
1331 pOffloadConfig->LsoV2.IPv6.IpExtensionHeadersSupported = NDIS_OFFLOAD_NOT_SUPPORTED;
1332 pOffloadConfig->LsoV2.IPv6.TcpOptionsSupported = NDIS_OFFLOAD_NOT_SUPPORTED;
1333}
1334
1335VOID vboxNetLwfWinStatus(IN NDIS_HANDLE hModuleCtx, IN PNDIS_STATUS_INDICATION pIndication)
1336{
1337 LogFlow(("==>vboxNetLwfWinStatus: module=%p\n", hModuleCtx));
1338 PVBOXNETLWF_MODULE pModuleCtx = (PVBOXNETLWF_MODULE)hModuleCtx;
1339 Log(("vboxNetLwfWinStatus: Got status indication: %s\n", vboxNetLwfWinStatusToText(pIndication->StatusCode)));
1340 switch (pIndication->StatusCode)
1341 {
1342 case NDIS_STATUS_PACKET_FILTER:
1343 vboxNetLwfWinDumpFilterTypes(*(ULONG*)pIndication->StatusBuffer);
1344 vboxNetLwfWinOverridePacketFiltersUp(pModuleCtx, (ULONG*)pIndication->StatusBuffer);
1345 Log(("vboxNetLwfWinStatus: Reporting status: %s\n", vboxNetLwfWinStatusToText(pIndication->StatusCode)));
1346 vboxNetLwfWinDumpFilterTypes(*(ULONG*)pIndication->StatusBuffer);
1347 break;
1348 case NDIS_STATUS_TASK_OFFLOAD_CURRENT_CONFIG:
1349 Log5(("vboxNetLwfWinStatus: offloading currently set to:\n"));
1350 vboxNetLwfWinDumpOffloadSettings((PNDIS_OFFLOAD)pIndication->StatusBuffer);
1351 vboxNetLwfWinUpdateSavedOffloadConfig(pModuleCtx, (PNDIS_OFFLOAD)pIndication->StatusBuffer);
1352 if (ASMAtomicReadBool(&pModuleCtx->fActive))
1353 vboxNetLwfWinDisableOffloading((PNDIS_OFFLOAD)pIndication->StatusBuffer);
1354 Log5(("vboxNetLwfWinStatus: reporting offloading up as:\n"));
1355 vboxNetLwfWinDumpOffloadSettings((PNDIS_OFFLOAD)pIndication->StatusBuffer);
1356 break;
1357 }
1358 NdisFIndicateStatus(pModuleCtx->hFilter, pIndication);
1359 LogFlow(("<==vboxNetLwfWinStatus\n"));
1360}
1361
1362static bool vboxNetLwfWinForwardToIntNet(PVBOXNETLWF_MODULE pModuleCtx, PNET_BUFFER_LIST pBufLists, uint32_t fSrc)
1363{
1364 /* We must not forward anything to the trunk unless it is ready to receive. */
1365 if (!ASMAtomicReadBool(&pModuleCtx->fActive))
1366 {
1367 Log(("vboxNetLwfWinForwardToIntNet: trunk is inactive, won't forward\n"));
1368 return false;
1369 }
1370
1371 AssertReturn(pModuleCtx->pNetFlt, false);
1372 AssertReturn(pModuleCtx->pNetFlt->pSwitchPort, false);
1373 AssertReturn(pModuleCtx->pNetFlt->pSwitchPort->pfnRecv, false);
1374 LogFlow(("==>vboxNetLwfWinForwardToIntNet: module=%p\n", pModuleCtx));
1375 Assert(pBufLists); /* The chain must contain at least one list */
1376 Assert(NET_BUFFER_LIST_NEXT_NBL(pBufLists) == NULL); /* The caller is supposed to unlink the list from the chain */
1377 /*
1378 * Even if NBL contains more than one buffer we are prepared to deal with it.
1379 * When any of buffers should not be dropped we keep the whole list. It is
1380 * better to leak some "unexpected" packets to the wire/host than to loose any.
1381 */
1382 bool fDropIt = false;
1383 bool fDontDrop = false;
1384 int nLists = 0;
1385 for (PNET_BUFFER_LIST pList = pBufLists; pList; pList = NET_BUFFER_LIST_NEXT_NBL(pList))
1386 {
1387 int nBuffers = 0;
1388 nLists++;
1389 for (PNET_BUFFER pBuf = NET_BUFFER_LIST_FIRST_NB(pList); pBuf; pBuf = NET_BUFFER_NEXT_NB(pBuf))
1390 {
1391 nBuffers++;
1392 PINTNETSG pSG = vboxNetLwfWinNBtoSG(pModuleCtx, pBuf);
1393 if (pSG)
1394 {
1395 vboxNetLwfWinDumpPacket(pSG, (fSrc & INTNETTRUNKDIR_WIRE)?"intnet <-- wire":"intnet <-- host");
1396 /* A bit paranoid, but we do not use any locks, so... */
1397 if (ASMAtomicReadBool(&pModuleCtx->fActive))
1398 if (pModuleCtx->pNetFlt->pSwitchPort->pfnRecv(pModuleCtx->pNetFlt->pSwitchPort, NULL, pSG, fSrc))
1399 fDropIt = true;
1400 else
1401 fDontDrop = true;
1402 vboxNetLwfWinDestroySG(pSG);
1403 }
1404 }
1405 Log(("vboxNetLwfWinForwardToIntNet: list=%d buffers=%d\n", nLists, nBuffers));
1406 }
1407 Log(("vboxNetLwfWinForwardToIntNet: lists=%d drop=%s don't=%s\n", nLists, fDropIt ? "true":"false", fDontDrop ? "true":"false"));
1408 LogFlow(("<==vboxNetLwfWinForwardToIntNet: return '%s'\n",
1409 fDropIt ? (fDontDrop ? "do not drop (some)" : "drop it") : "do not drop (any)"));
1410 return fDropIt && !fDontDrop; /* Drop the list if ALL its buffers are being dropped! */
1411}
1412
1413DECLINLINE(bool) vboxNetLwfWinIsRunning(PVBOXNETLWF_MODULE pModule)
1414{
1415 Log(("vboxNetLwfWinIsRunning: state=%d\n", ASMAtomicReadU32(&pModule->enmState)));
1416 return ASMAtomicReadU32(&pModule->enmState) == LwfState_Running;
1417}
1418
1419VOID vboxNetLwfWinSendNetBufferLists(IN NDIS_HANDLE hModuleCtx, IN PNET_BUFFER_LIST pBufLists, IN NDIS_PORT_NUMBER nPort, IN ULONG fFlags)
1420{
1421 size_t cb = 0;
1422 LogFlow(("==>vboxNetLwfWinSendNetBufferLists: module=%p\n", hModuleCtx));
1423 PVBOXNETLWF_MODULE pModule = (PVBOXNETLWF_MODULE)hModuleCtx;
1424
1425 if (!ASMAtomicReadBool(&pModule->fActive))
1426 {
1427 /*
1428 * The trunk is inactive, jusp pass along all packets to the next
1429 * underlying driver.
1430 */
1431 NdisFSendNetBufferLists(pModule->hFilter, pBufLists, nPort, fFlags);
1432 return;
1433 }
1434
1435 if (vboxNetLwfWinIsRunning(pModule))
1436 {
1437 PNET_BUFFER_LIST pNext = NULL;
1438 PNET_BUFFER_LIST pDropHead = NULL;
1439 PNET_BUFFER_LIST pDropTail = NULL;
1440 PNET_BUFFER_LIST pPassHead = NULL;
1441 PNET_BUFFER_LIST pPassTail = NULL;
1442 for (PNET_BUFFER_LIST pList = pBufLists; pList; pList = pNext)
1443 {
1444 pNext = NET_BUFFER_LIST_NEXT_NBL(pList);
1445 NET_BUFFER_LIST_NEXT_NBL(pList) = NULL; /* Unlink */
1446 if (vboxNetLwfWinForwardToIntNet(pModule, pList, INTNETTRUNKDIR_HOST))
1447 {
1448 NET_BUFFER_LIST_STATUS(pList) = NDIS_STATUS_SUCCESS;
1449 if (pDropHead)
1450 {
1451 NET_BUFFER_LIST_NEXT_NBL(pDropTail) = pList;
1452 pDropTail = pList;
1453 }
1454 else
1455 pDropHead = pDropTail = pList;
1456 }
1457 else
1458 {
1459 if (pPassHead)
1460 {
1461 NET_BUFFER_LIST_NEXT_NBL(pPassTail) = pList;
1462 pPassTail = pList;
1463 }
1464 else
1465 pPassHead = pPassTail = pList;
1466 }
1467 }
1468 Assert((pBufLists == pPassHead) || (pBufLists == pDropHead));
1469 if (pPassHead)
1470 {
1471 vboxNetLwfWinDumpPackets("vboxNetLwfWinSendNetBufferLists: passing down", pPassHead);
1472 NdisFSendNetBufferLists(pModule->hFilter, pBufLists, nPort, fFlags);
1473 }
1474 if (pDropHead)
1475 {
1476 vboxNetLwfWinDumpPackets("vboxNetLwfWinSendNetBufferLists: consumed", pDropHead);
1477 NdisFSendNetBufferListsComplete(pModule->hFilter, pDropHead,
1478 fFlags & NDIS_SEND_FLAGS_DISPATCH_LEVEL ? NDIS_SEND_COMPLETE_FLAGS_DISPATCH_LEVEL : 0);
1479 }
1480 }
1481 else
1482 {
1483 for (PNET_BUFFER_LIST pList = pBufLists; pList; pList = NET_BUFFER_LIST_NEXT_NBL(pList))
1484 {
1485 NET_BUFFER_LIST_STATUS(pList) = NDIS_STATUS_PAUSED;
1486 }
1487 vboxNetLwfWinDumpPackets("vboxNetLwfWinSendNetBufferLists: consumed", pBufLists);
1488 NdisFSendNetBufferListsComplete(pModule->hFilter, pBufLists,
1489 fFlags & NDIS_SEND_FLAGS_DISPATCH_LEVEL ? NDIS_SEND_COMPLETE_FLAGS_DISPATCH_LEVEL : 0);
1490
1491 }
1492 LogFlow(("<==vboxNetLwfWinSendNetBufferLists\n"));
1493}
1494
1495VOID vboxNetLwfWinSendNetBufferListsComplete(IN NDIS_HANDLE hModuleCtx, IN PNET_BUFFER_LIST pBufLists, IN ULONG fFlags)
1496{
1497 size_t cb = 0;
1498 LogFlow(("==>vboxNetLwfWinSendNetBufferListsComplete: module=%p\n", hModuleCtx));
1499 PVBOXNETLWF_MODULE pModule = (PVBOXNETLWF_MODULE)hModuleCtx;
1500 PNET_BUFFER_LIST pList = pBufLists;
1501 PNET_BUFFER_LIST pNextList;
1502 PNET_BUFFER_LIST pPrevList = NULL;
1503 while (pList)
1504 {
1505 pNextList = NET_BUFFER_LIST_NEXT_NBL(pList);
1506 if (pList->SourceHandle == pModule->hFilter)
1507 {
1508 /* We allocated this NET_BUFFER_LIST, let's free it up */
1509 Assert(NET_BUFFER_LIST_FIRST_NB(pList));
1510 Assert(NET_BUFFER_FIRST_MDL(NET_BUFFER_LIST_FIRST_NB(pList)));
1511 /*
1512 * All our NBLs hold a single NB each, no need to iterate over a list.
1513 * There is no need to free an associated NB explicitly either, as it was
1514 * preallocated with NBL structure.
1515 */
1516 Assert(!NET_BUFFER_NEXT_NB(NET_BUFFER_LIST_FIRST_NB(pList)));
1517 vboxNetLwfWinFreeMdlChain(NET_BUFFER_FIRST_MDL(NET_BUFFER_LIST_FIRST_NB(pList)));
1518 /* Unlink this list from the chain */
1519 if (pPrevList)
1520 NET_BUFFER_LIST_NEXT_NBL(pPrevList) = pNextList;
1521 else
1522 pBufLists = pNextList;
1523 Log(("vboxNetLwfWinSendNetBufferListsComplete: our list %p, next=%p, previous=%p, head=%p\n", pList, pNextList, pPrevList, pBufLists));
1524 NdisFreeNetBufferList(pList);
1525#ifdef VBOXNETLWF_SYNC_SEND
1526 Log4(("vboxNetLwfWinSendNetBufferListsComplete: freed NBL+NB 0x%p\n", pList));
1527 KeSetEvent(&pModule->EventWire, 0, FALSE);
1528#else /* !VBOXNETLWF_SYNC_SEND */
1529 Log4(("vboxNetLwfWinSendNetBufferListsComplete: freed NBL+NB+MDL+Data 0x%p\n", pList));
1530 Assert(ASMAtomicReadS32(&pModule->cPendingBuffers) > 0);
1531 if (ASMAtomicDecS32(&pModule->cPendingBuffers) == 0)
1532 NdisSetEvent(&pModule->EventSendComplete);
1533#endif /* !VBOXNETLWF_SYNC_SEND */
1534 }
1535 else
1536 {
1537 pPrevList = pList;
1538 Log(("vboxNetLwfWinSendNetBufferListsComplete: passing list %p, next=%p, previous=%p, head=%p\n", pList, pNextList, pPrevList, pBufLists));
1539 }
1540 pList = pNextList;
1541 }
1542 if (pBufLists)
1543 {
1544 /* There are still lists remaining in the chain, pass'em up */
1545 NdisFSendNetBufferListsComplete(pModule->hFilter, pBufLists, fFlags);
1546 }
1547 LogFlow(("<==vboxNetLwfWinSendNetBufferListsComplete\n"));
1548}
1549
1550VOID vboxNetLwfWinReceiveNetBufferLists(IN NDIS_HANDLE hModuleCtx,
1551 IN PNET_BUFFER_LIST pBufLists,
1552 IN NDIS_PORT_NUMBER nPort,
1553 IN ULONG nBufLists,
1554 IN ULONG fFlags)
1555{
1556 /// @todo Do we need loopback handling?
1557 LogFlow(("==>vboxNetLwfWinReceiveNetBufferLists: module=%p\n", hModuleCtx));
1558 PVBOXNETLWF_MODULE pModule = (PVBOXNETLWF_MODULE)hModuleCtx;
1559
1560 if (!ASMAtomicReadBool(&pModule->fActive))
1561 {
1562 /*
1563 * The trunk is inactive, jusp pass along all packets to the next
1564 * overlying driver.
1565 */
1566 NdisFIndicateReceiveNetBufferLists(pModule->hFilter, pBufLists, nPort, nBufLists, fFlags);
1567 LogFlow(("<==vboxNetLwfWinReceiveNetBufferLists: inactive trunk\n"));
1568 return;
1569 }
1570
1571 if (vboxNetLwfWinIsRunning(pModule))
1572 {
1573 if (NDIS_TEST_RECEIVE_CANNOT_PEND(fFlags))
1574 {
1575 /* We do not own NBLs so we do not need to return them */
1576 /* First we need to scan through the list to see if some packets must be dropped */
1577 bool bDropIt = false;
1578 for (PNET_BUFFER_LIST pList = pBufLists; pList; pList = NET_BUFFER_LIST_NEXT_NBL(pList))
1579 {
1580 PNET_BUFFER_LIST pNext = NET_BUFFER_LIST_NEXT_NBL(pList);
1581 NET_BUFFER_LIST_NEXT_NBL(pList) = NULL; /* Unlink temporarily */
1582 if (vboxNetLwfWinForwardToIntNet(pModule, pList, INTNETTRUNKDIR_WIRE))
1583 bDropIt = true;
1584 NET_BUFFER_LIST_NEXT_NBL(pList) = pNext; /* Restore the link */
1585 }
1586 if (bDropIt)
1587 {
1588 /* Some NBLs must be dropped, indicate selectively one by one */
1589 for (PNET_BUFFER_LIST pList = pBufLists; pList; pList = NET_BUFFER_LIST_NEXT_NBL(pList))
1590 {
1591 PNET_BUFFER_LIST pNext = NET_BUFFER_LIST_NEXT_NBL(pList);
1592 NET_BUFFER_LIST_NEXT_NBL(pList) = NULL; /* Unlink temporarily */
1593 vboxNetLwfWinDumpPackets("vboxNetLwfWinReceiveNetBufferLists: passing up", pList);
1594 NdisFIndicateReceiveNetBufferLists(pModule->hFilter, pList, nPort, nBufLists, fFlags);
1595 NET_BUFFER_LIST_NEXT_NBL(pList) = pNext; /* Restore the link */
1596 }
1597 }
1598 else
1599 {
1600 /* All NBLs must be indicated, do it in bulk. */
1601 vboxNetLwfWinDumpPackets("vboxNetLwfWinReceiveNetBufferLists: passing up", pBufLists);
1602 NdisFIndicateReceiveNetBufferLists(pModule->hFilter, pBufLists, nPort, nBufLists, fFlags);
1603 }
1604 }
1605 else
1606 {
1607 /* We collect dropped NBLs in a separate list in order to "return" them. */
1608 PNET_BUFFER_LIST pNext = NULL;
1609 PNET_BUFFER_LIST pDropHead = NULL;
1610 PNET_BUFFER_LIST pDropTail = NULL;
1611 PNET_BUFFER_LIST pPassHead = NULL;
1612 PNET_BUFFER_LIST pPassTail = NULL;
1613 ULONG nDrop = 0, nPass = 0;
1614 for (PNET_BUFFER_LIST pList = pBufLists; pList; pList = pNext)
1615 {
1616 pNext = NET_BUFFER_LIST_NEXT_NBL(pList);
1617 NET_BUFFER_LIST_NEXT_NBL(pList) = NULL; /* Unlink */
1618 if (vboxNetLwfWinForwardToIntNet(pModule, pList, INTNETTRUNKDIR_WIRE))
1619 {
1620 if (nDrop++)
1621 {
1622 NET_BUFFER_LIST_NEXT_NBL(pDropTail) = pList;
1623 pDropTail = pList;
1624 }
1625 else
1626 pDropHead = pDropTail = pList;
1627 }
1628 else
1629 {
1630 if (nPass++)
1631 {
1632 NET_BUFFER_LIST_NEXT_NBL(pPassTail) = pList;
1633 pPassTail = pList;
1634 }
1635 else
1636 pPassHead = pPassTail = pList;
1637 }
1638 }
1639 Assert((pBufLists == pPassHead) || (pBufLists == pDropHead));
1640 Assert(nDrop + nPass == nBufLists);
1641 if (pPassHead)
1642 {
1643 vboxNetLwfWinDumpPackets("vboxNetLwfWinReceiveNetBufferLists: passing up", pPassHead);
1644 NdisFIndicateReceiveNetBufferLists(pModule->hFilter, pPassHead, nPort, nPass, fFlags);
1645 }
1646 if (pDropHead)
1647 {
1648 vboxNetLwfWinDumpPackets("vboxNetLwfWinReceiveNetBufferLists: consumed", pDropHead);
1649 NdisFReturnNetBufferLists(pModule->hFilter, pDropHead,
1650 fFlags & NDIS_RECEIVE_FLAGS_DISPATCH_LEVEL ? NDIS_RETURN_FLAGS_DISPATCH_LEVEL : 0);
1651 }
1652 }
1653
1654 }
1655 else
1656 {
1657 vboxNetLwfWinDumpPackets("vboxNetLwfWinReceiveNetBufferLists: consumed", pBufLists);
1658 if ((fFlags & NDIS_RECEIVE_FLAGS_RESOURCES) == 0)
1659 NdisFReturnNetBufferLists(pModule->hFilter, pBufLists,
1660 fFlags & NDIS_RECEIVE_FLAGS_DISPATCH_LEVEL ? NDIS_RETURN_FLAGS_DISPATCH_LEVEL : 0);
1661 }
1662 LogFlow(("<==vboxNetLwfWinReceiveNetBufferLists\n"));
1663}
1664
1665VOID vboxNetLwfWinReturnNetBufferLists(IN NDIS_HANDLE hModuleCtx, IN PNET_BUFFER_LIST pBufLists, IN ULONG fFlags)
1666{
1667 size_t cb = 0;
1668 LogFlow(("==>vboxNetLwfWinReturnNetBufferLists: module=%p\n", hModuleCtx));
1669 PVBOXNETLWF_MODULE pModule = (PVBOXNETLWF_MODULE)hModuleCtx;
1670 PNET_BUFFER_LIST pList = pBufLists;
1671 PNET_BUFFER_LIST pNextList;
1672 PNET_BUFFER_LIST pPrevList = NULL;
1673 /** @todo Move common part into a separate function to be used by vboxNetLwfWinSendNetBufferListsComplete() as well */
1674 while (pList)
1675 {
1676 pNextList = NET_BUFFER_LIST_NEXT_NBL(pList);
1677 if (pList->SourceHandle == pModule->hFilter)
1678 {
1679 /* We allocated this NET_BUFFER_LIST, let's free it up */
1680 Assert(NET_BUFFER_LIST_FIRST_NB(pList));
1681 Assert(NET_BUFFER_FIRST_MDL(NET_BUFFER_LIST_FIRST_NB(pList)));
1682 /*
1683 * All our NBLs hold a single NB each, no need to iterate over a list.
1684 * There is no need to free an associated NB explicitly either, as it was
1685 * preallocated with NBL structure.
1686 */
1687 vboxNetLwfWinFreeMdlChain(NET_BUFFER_FIRST_MDL(NET_BUFFER_LIST_FIRST_NB(pList)));
1688 /* Unlink this list from the chain */
1689 if (pPrevList)
1690 NET_BUFFER_LIST_NEXT_NBL(pPrevList) = pNextList;
1691 else
1692 pBufLists = pNextList;
1693 NdisFreeNetBufferList(pList);
1694#ifdef VBOXNETLWF_SYNC_SEND
1695 Log4(("vboxNetLwfWinReturnNetBufferLists: freed NBL+NB 0x%p\n", pList));
1696 KeSetEvent(&pModule->EventHost, 0, FALSE);
1697#else /* !VBOXNETLWF_SYNC_SEND */
1698 Log4(("vboxNetLwfWinReturnNetBufferLists: freed NBL+NB+MDL+Data 0x%p\n", pList));
1699 Assert(ASMAtomicReadS32(&pModule->cPendingBuffers) > 0);
1700 if (ASMAtomicDecS32(&pModule->cPendingBuffers) == 0)
1701 NdisSetEvent(&pModule->EventSendComplete);
1702#endif /* !VBOXNETLWF_SYNC_SEND */
1703 }
1704 else
1705 pPrevList = pList;
1706 pList = pNextList;
1707 }
1708 if (pBufLists)
1709 {
1710 /* There are still lists remaining in the chain, pass'em up */
1711 NdisFReturnNetBufferLists(pModule->hFilter, pBufLists, fFlags);
1712 }
1713 LogFlow(("<==vboxNetLwfWinReturnNetBufferLists\n"));
1714}
1715
1716/**
1717 * register the filter driver
1718 */
1719DECLHIDDEN(NDIS_STATUS) vboxNetLwfWinRegister(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPathStr)
1720{
1721 NDIS_FILTER_DRIVER_CHARACTERISTICS FChars;
1722 NDIS_STRING FriendlyName;
1723 NDIS_STRING UniqueName;
1724 NDIS_STRING ServiceName;
1725
1726 NdisInitUnicodeString(&FriendlyName, VBOXNETLWF_NAME_FRIENDLY);
1727 NdisInitUnicodeString(&UniqueName, VBOXNETLWF_NAME_UNIQUE);
1728 NdisInitUnicodeString(&ServiceName, VBOXNETLWF_NAME_SERVICE);
1729
1730 NdisZeroMemory(&FChars, sizeof (FChars));
1731
1732 FChars.Header.Type = NDIS_OBJECT_TYPE_FILTER_DRIVER_CHARACTERISTICS;
1733 FChars.Header.Size = sizeof(NDIS_FILTER_DRIVER_CHARACTERISTICS);
1734 FChars.Header.Revision = NDIS_FILTER_CHARACTERISTICS_REVISION_1;
1735
1736 FChars.MajorNdisVersion = VBOXNETLWF_VERSION_NDIS_MAJOR;
1737 FChars.MinorNdisVersion = VBOXNETLWF_VERSION_NDIS_MINOR;
1738
1739 FChars.FriendlyName = FriendlyName;
1740 FChars.UniqueName = UniqueName;
1741 FChars.ServiceName = ServiceName;
1742
1743 /* Mandatory functions */
1744 FChars.AttachHandler = vboxNetLwfWinAttach;
1745 FChars.DetachHandler = vboxNetLwfWinDetach;
1746 FChars.RestartHandler = vboxNetLwfWinRestart;
1747 FChars.PauseHandler = vboxNetLwfWinPause;
1748
1749 /* Optional functions, non changeble at run-time */
1750 FChars.OidRequestHandler = vboxNetLwfWinOidRequest;
1751 FChars.OidRequestCompleteHandler = vboxNetLwfWinOidRequestComplete;
1752 //FChars.CancelOidRequestHandler = vboxNetLwfWinCancelOidRequest;
1753 FChars.StatusHandler = vboxNetLwfWinStatus;
1754 //FChars.NetPnPEventHandler = vboxNetLwfWinPnPEvent;
1755
1756 /* Datapath functions */
1757 FChars.SendNetBufferListsHandler = vboxNetLwfWinSendNetBufferLists;
1758 FChars.SendNetBufferListsCompleteHandler = vboxNetLwfWinSendNetBufferListsComplete;
1759 FChars.ReceiveNetBufferListsHandler = vboxNetLwfWinReceiveNetBufferLists;
1760 FChars.ReturnNetBufferListsHandler = vboxNetLwfWinReturnNetBufferLists;
1761
1762 pDriverObject->DriverUnload = vboxNetLwfWinUnloadDriver;
1763
1764 NDIS_STATUS Status;
1765 g_VBoxNetLwfGlobals.hFilterDriver = NULL;
1766 Log(("vboxNetLwfWinRegister: registering filter driver...\n"));
1767 Status = NdisFRegisterFilterDriver(pDriverObject,
1768 (NDIS_HANDLE)&g_VBoxNetLwfGlobals,
1769 &FChars,
1770 &g_VBoxNetLwfGlobals.hFilterDriver);
1771 Assert(Status == STATUS_SUCCESS);
1772 if (Status == STATUS_SUCCESS)
1773 {
1774 Log(("vboxNetLwfWinRegister: successfully registered filter driver; registering device...\n"));
1775 Status = vboxNetLwfWinDevCreate(&g_VBoxNetLwfGlobals);
1776 Assert(Status == STATUS_SUCCESS);
1777 Log(("vboxNetLwfWinRegister: vboxNetLwfWinDevCreate() returned 0x%x\n", Status));
1778 }
1779 else
1780 {
1781 Log(("ERROR! vboxNetLwfWinRegister: failed to register filter driver, status=0x%x", Status));
1782 }
1783 return Status;
1784}
1785
1786static int vboxNetLwfWinStartInitIdcThread()
1787{
1788 int rc = VERR_INVALID_STATE;
1789
1790 if (ASMAtomicCmpXchgU32(&g_VBoxNetLwfGlobals.enmIdcState, LwfIdcState_Connecting, LwfIdcState_Disconnected))
1791 {
1792 Log(("vboxNetLwfWinStartInitIdcThread: IDC state change Diconnected -> Connecting\n"));
1793
1794 NTSTATUS Status = PsCreateSystemThread(&g_VBoxNetLwfGlobals.hInitIdcThread,
1795 THREAD_ALL_ACCESS,
1796 NULL,
1797 NULL,
1798 NULL,
1799 vboxNetLwfWinInitIdcWorker,
1800 &g_VBoxNetLwfGlobals);
1801 Log(("vboxNetLwfWinStartInitIdcThread: create IDC initialization thread, status=0x%x\n", Status));
1802 if (Status != STATUS_SUCCESS)
1803 {
1804 LogRel(("NETLWF: IDC initialization failed (system thread creation, status=0x%x)\n", Status));
1805 /*
1806 * We failed to init IDC and there will be no second chance.
1807 */
1808 Log(("vboxNetLwfWinStartInitIdcThread: IDC state change Connecting -> Diconnected\n"));
1809 ASMAtomicWriteU32(&g_VBoxNetLwfGlobals.enmIdcState, LwfIdcState_Disconnected);
1810 }
1811 rc = RTErrConvertFromNtStatus(Status);
1812 }
1813 return rc;
1814}
1815
1816static void vboxNetLwfWinStopInitIdcThread()
1817{
1818}
1819
1820
1821RT_C_DECLS_BEGIN
1822
1823NTSTATUS DriverEntry(IN PDRIVER_OBJECT pDriverObject, IN PUNICODE_STRING pRegistryPath);
1824
1825RT_C_DECLS_END
1826
1827NTSTATUS DriverEntry(IN PDRIVER_OBJECT pDriverObject, IN PUNICODE_STRING pRegistryPath)
1828{
1829 NDIS_STATUS Status = NDIS_STATUS_SUCCESS;
1830 int rc;
1831
1832 /* the idc registration is initiated via IOCTL since our driver
1833 * can be loaded when the VBoxDrv is not in case we are a Ndis IM driver */
1834 rc = vboxNetLwfWinInitBase();
1835 AssertRC(rc);
1836 if (RT_SUCCESS(rc))
1837 {
1838 NdisZeroMemory(&g_VBoxNetLwfGlobals, sizeof (g_VBoxNetLwfGlobals));
1839 RTListInit(&g_VBoxNetLwfGlobals.listModules);
1840 NdisAllocateSpinLock(&g_VBoxNetLwfGlobals.Lock);
1841 /*
1842 * We choose to ignore IDC initialization errors here because if we fail to load
1843 * our filter the upper protocols won't bind to the associated adapter, causing
1844 * network failure at the host. Better to have non-working filter than broken
1845 * networking on the host.
1846 */
1847 rc = vboxNetLwfWinStartInitIdcThread();
1848 AssertRC(rc);
1849
1850 Status = vboxNetLwfWinRegister(pDriverObject, pRegistryPath);
1851 Assert(Status == STATUS_SUCCESS);
1852 if (Status == NDIS_STATUS_SUCCESS)
1853 {
1854 Log(("NETLWF: started successfully\n"));
1855 return STATUS_SUCCESS;
1856 }
1857 NdisFreeSpinLock(&g_VBoxNetLwfGlobals.Lock);
1858 vboxNetLwfWinFini();
1859 }
1860 else
1861 {
1862 Status = NDIS_STATUS_FAILURE;
1863 }
1864
1865 return Status;
1866}
1867
1868
1869static VOID vboxNetLwfWinUnloadDriver(IN PDRIVER_OBJECT pDriver)
1870{
1871 LogFlow(("==>vboxNetLwfWinUnloadDriver: driver=%p\n", pDriver));
1872 vboxNetLwfWinDevDestroy(&g_VBoxNetLwfGlobals);
1873 NdisFDeregisterFilterDriver(g_VBoxNetLwfGlobals.hFilterDriver);
1874 NdisFreeSpinLock(&g_VBoxNetLwfGlobals.Lock);
1875 LogFlow(("<==vboxNetLwfWinUnloadDriver\n"));
1876 vboxNetLwfWinFini();
1877}
1878
1879static const char *vboxNetLwfWinIdcStateToText(uint32_t enmState)
1880{
1881 switch (enmState)
1882 {
1883 case LwfIdcState_Disconnected: return "Disconnected";
1884 case LwfIdcState_Connecting: return "Connecting";
1885 case LwfIdcState_Connected: return "Connected";
1886 case LwfIdcState_Stopping: return "Stopping";
1887 }
1888 return "Unknown";
1889}
1890
1891static VOID vboxNetLwfWinInitIdcWorker(PVOID pvContext)
1892{
1893 int rc;
1894 PVBOXNETLWFGLOBALS pGlobals = (PVBOXNETLWFGLOBALS)pvContext;
1895
1896 while (ASMAtomicReadU32(&pGlobals->enmIdcState) == LwfIdcState_Connecting)
1897 {
1898 rc = vboxNetFltInitIdc(&g_VBoxNetFltGlobals);
1899 if (RT_SUCCESS(rc))
1900 {
1901 if (!ASMAtomicCmpXchgU32(&pGlobals->enmIdcState, LwfIdcState_Connected, LwfIdcState_Connecting))
1902 {
1903 /* The state has been changed (the only valid transition is to "Stopping"), undo init */
1904 rc = vboxNetFltTryDeleteIdc(&g_VBoxNetFltGlobals);
1905 Log(("vboxNetLwfWinInitIdcWorker: state change (Connecting -> %s) while initializing IDC, deleted IDC, rc=0x%x\n",
1906 vboxNetLwfWinIdcStateToText(ASMAtomicReadU32(&pGlobals->enmIdcState)), rc));
1907 }
1908 else
1909 {
1910 Log(("vboxNetLwfWinInitIdcWorker: IDC state change Connecting -> Connected\n"));
1911 }
1912 }
1913 else
1914 {
1915 LARGE_INTEGER WaitIn100nsUnits;
1916 WaitIn100nsUnits.QuadPart = -(LONGLONG)10000000; /* 1 sec */
1917 KeDelayExecutionThread(KernelMode, FALSE /* non-alertable */, &WaitIn100nsUnits);
1918 }
1919 }
1920 PsTerminateSystemThread(STATUS_SUCCESS);
1921}
1922
1923static int vboxNetLwfWinTryFiniIdc()
1924{
1925 int rc = VINF_SUCCESS;
1926 NTSTATUS Status;
1927 PKTHREAD pThread = NULL;
1928 uint32_t enmPrevState = ASMAtomicXchgU32(&g_VBoxNetLwfGlobals.enmIdcState, LwfIdcState_Stopping);
1929
1930 Log(("vboxNetLwfWinTryFiniIdc: IDC state change %s -> Stopping\n", vboxNetLwfWinIdcStateToText(enmPrevState)));
1931
1932 switch (enmPrevState)
1933 {
1934 case LwfIdcState_Disconnected:
1935 /* Have not even attempted to connect -- nothing to do. */
1936 break;
1937 case LwfIdcState_Stopping:
1938 /* Impossible, but another thread is alreading doing FiniIdc, bail out */
1939 Log(("ERROR! vboxNetLwfWinTryFiniIdc: called in 'Stopping' state\n"));
1940 rc = VERR_INVALID_STATE;
1941 break;
1942 case LwfIdcState_Connecting:
1943 /* the worker thread is running, let's wait for it to stop */
1944 Status = ObReferenceObjectByHandle(g_VBoxNetLwfGlobals.hInitIdcThread,
1945 THREAD_ALL_ACCESS, NULL, KernelMode,
1946 (PVOID*)&pThread, NULL);
1947 if (Status == STATUS_SUCCESS)
1948 {
1949 KeWaitForSingleObject(pThread, Executive, KernelMode, FALSE, NULL);
1950 ObDereferenceObject(pThread);
1951 }
1952 else
1953 {
1954 Log(("ERROR! vboxNetLwfWinTryFiniIdc: ObReferenceObjectByHandle(%p) failed with 0x%x\n",
1955 g_VBoxNetLwfGlobals.hInitIdcThread, Status));
1956 }
1957 rc = RTErrConvertFromNtStatus(Status);
1958 break;
1959 case LwfIdcState_Connected:
1960 /* the worker succeeded in IDC init and terminated */
1961 rc = vboxNetFltTryDeleteIdc(&g_VBoxNetFltGlobals);
1962 Log(("vboxNetLwfWinTryFiniIdc: deleted IDC, rc=0x%x\n", rc));
1963 break;
1964 }
1965 return rc;
1966}
1967
1968static void vboxNetLwfWinFiniBase()
1969{
1970 vboxNetFltDeleteGlobals(&g_VBoxNetFltGlobals);
1971
1972 /*
1973 * Undo the work done during start (in reverse order).
1974 */
1975 memset(&g_VBoxNetFltGlobals, 0, sizeof(g_VBoxNetFltGlobals));
1976
1977 RTLogDestroy(RTLogRelSetDefaultInstance(NULL));
1978 RTLogDestroy(RTLogSetDefaultInstance(NULL));
1979
1980 RTR0Term();
1981}
1982
1983static int vboxNetLwfWinInitBase()
1984{
1985 int rc = RTR0Init(0);
1986 if (!RT_SUCCESS(rc))
1987 return rc;
1988
1989 memset(&g_VBoxNetFltGlobals, 0, sizeof(g_VBoxNetFltGlobals));
1990 rc = vboxNetFltInitGlobals(&g_VBoxNetFltGlobals);
1991 if (!RT_SUCCESS(rc))
1992 RTR0Term();
1993
1994 return rc;
1995}
1996
1997static int vboxNetLwfWinFini()
1998{
1999 int rc = vboxNetLwfWinTryFiniIdc();
2000 if (RT_SUCCESS(rc))
2001 {
2002 vboxNetLwfWinFiniBase();
2003 }
2004 return rc;
2005}
2006
2007
2008/*
2009 *
2010 * The OS specific interface definition
2011 *
2012 */
2013
2014
2015bool vboxNetFltOsMaybeRediscovered(PVBOXNETFLTINS pThis)
2016{
2017 LogFlow(("==>vboxNetFltOsMaybeRediscovered: instance=%p\n", pThis));
2018 LogFlow(("<==vboxNetFltOsMaybeRediscovered: return %RTbool\n", !ASMAtomicUoReadBool(&pThis->fDisconnectedFromHost)));
2019 /* AttachToInterface true if disconnected */
2020 return !ASMAtomicUoReadBool(&pThis->fDisconnectedFromHost);
2021}
2022
2023int vboxNetFltPortOsXmit(PVBOXNETFLTINS pThis, void *pvIfData, PINTNETSG pSG, uint32_t fDst)
2024{
2025 int rc = VINF_SUCCESS;
2026
2027 PVBOXNETLWF_MODULE pModule = (PVBOXNETLWF_MODULE)pThis->u.s.WinIf.hModuleCtx;
2028 LogFlow(("==>vboxNetFltPortOsXmit: instance=%p module=%p\n", pThis, pModule));
2029 if (!pModule)
2030 {
2031 LogFlow(("<==vboxNetFltPortOsXmit: pModule is null, return %d\n", VERR_INTERNAL_ERROR));
2032 return VERR_INTERNAL_ERROR;
2033 }
2034 /* Prevent going into "paused" state until all transmissions have been completed. */
2035 NDIS_WAIT_FOR_MUTEX(&pModule->InTransmit);
2036 /* Ignore all sends if the stack is paused or being paused, etc... */
2037 if (!vboxNetLwfWinIsRunning(pModule))
2038 {
2039 NDIS_RELEASE_MUTEX(&pModule->InTransmit);
2040 return VINF_SUCCESS;
2041 }
2042
2043 const char *pszDir = (fDst & INTNETTRUNKDIR_WIRE) ?
2044 ( (fDst & INTNETTRUNKDIR_HOST) ? "intnet --> all" : "intnet --> wire" ) : "intnet --> host";
2045 vboxNetLwfWinDumpPacket(pSG, pszDir);
2046 /*
2047 * There are two possible strategies to deal with incoming SGs:
2048 * 1) make a copy of data and complete asynchronously;
2049 * 2) complete synchronously using the original data buffers.
2050 * Before we consider implementing (1) it is quite interesting to see
2051 * how well (2) performs. So we block until our requests are complete.
2052 * Actually there is third possibility -- to use SG retain/release
2053 * callbacks, but those seem not be fully implemented yet.
2054 * Note that ansynchronous completion will require different implementation
2055 * of vboxNetLwfWinPause(), not relying on InTransmit mutex.
2056 */
2057#ifdef VBOXNETLWF_SYNC_SEND
2058 PVOID aEvents[2]; /* To wire and to host */
2059 ULONG nEvents = 0;
2060 LARGE_INTEGER timeout;
2061 timeout.QuadPart = -(LONGLONG)10000000; /* 1 sec */
2062#endif /* VBOXNETLWF_SYNC_SEND */
2063 if (fDst & INTNETTRUNKDIR_WIRE)
2064 {
2065 PNET_BUFFER_LIST pBufList = vboxNetLwfWinSGtoNB(pModule, pSG);
2066 if (pBufList)
2067 {
2068#ifdef VBOXNETLWF_SYNC_SEND
2069 aEvents[nEvents++] = &pModule->EventWire;
2070#else /* !VBOXNETLWF_SYNC_SEND */
2071 if (ASMAtomicIncS32(&pModule->cPendingBuffers) == 1)
2072 NdisResetEvent(&pModule->EventSendComplete);
2073#endif /* !VBOXNETLWF_SYNC_SEND */
2074 NdisFSendNetBufferLists(pModule->hFilter, pBufList, NDIS_DEFAULT_PORT_NUMBER, 0); /** @todo sendFlags! */
2075 }
2076 }
2077 if (fDst & INTNETTRUNKDIR_HOST)
2078 {
2079 PNET_BUFFER_LIST pBufList = vboxNetLwfWinSGtoNB(pModule, pSG);
2080 if (pBufList)
2081 {
2082#ifdef VBOXNETLWF_SYNC_SEND
2083 aEvents[nEvents++] = &pModule->EventHost;
2084#else /* !VBOXNETLWF_SYNC_SEND */
2085 if (ASMAtomicIncS32(&pModule->cPendingBuffers) == 1)
2086 NdisResetEvent(&pModule->EventSendComplete);
2087#endif /* !VBOXNETLWF_SYNC_SEND */
2088 NdisFIndicateReceiveNetBufferLists(pModule->hFilter, pBufList, NDIS_DEFAULT_PORT_NUMBER, 1, 0);
2089 }
2090 }
2091#ifdef VBOXNETLWF_SYNC_SEND
2092 if (nEvents)
2093 {
2094 NTSTATUS Status = KeWaitForMultipleObjects(nEvents, aEvents, WaitAll, Executive, KernelMode, FALSE, &timeout, NULL);
2095 if (Status != STATUS_SUCCESS)
2096 {
2097 Log(("ERROR! vboxNetFltPortOsXmit: KeWaitForMultipleObjects() failed with 0x%x\n", Status));
2098 if (Status == STATUS_TIMEOUT)
2099 rc = VERR_TIMEOUT;
2100 else
2101 rc = RTErrConvertFromNtStatus(Status);
2102 }
2103 }
2104#endif /* VBOXNETLWF_SYNC_SEND */
2105 NDIS_RELEASE_MUTEX(&pModule->InTransmit);
2106
2107 LogFlow(("<==vboxNetFltPortOsXmit: return %d\n", rc));
2108 return rc;
2109}
2110
2111
2112NDIS_IO_WORKITEM_FUNCTION vboxNetLwfWinToggleOffloading;
2113
2114VOID vboxNetLwfWinToggleOffloading(PVOID WorkItemContext, NDIS_HANDLE NdisIoWorkItemHandle)
2115{
2116 /* WARNING! Call this with IRQL=Passive! */
2117 PVBOXNETLWF_MODULE pModuleCtx = (PVBOXNETLWF_MODULE)WorkItemContext;
2118
2119 if (ASMAtomicReadBool(&pModuleCtx->fActive))
2120 {
2121 /* Disable offloading temporarily by indicating offload config change. */
2122 /** @todo Be sure to revise this when implementing offloading support! */
2123 NDIS_OFFLOAD OffloadConfig;
2124 if (pModuleCtx->fOffloadConfigValid)
2125 {
2126 OffloadConfig = pModuleCtx->SavedOffloadConfig;
2127 vboxNetLwfWinDisableOffloading(&OffloadConfig);
2128 }
2129 else
2130 {
2131 DbgPrint("VBoxNetLwf: no saved offload config to modify for %s\n", pModuleCtx->szMiniportName);
2132 NdisZeroMemory(&OffloadConfig, sizeof(OffloadConfig));
2133 OffloadConfig.Header.Type = NDIS_OBJECT_TYPE_OFFLOAD;
2134 OffloadConfig.Header.Revision = NDIS_OFFLOAD_REVISION_1;
2135 OffloadConfig.Header.Size = NDIS_SIZEOF_NDIS_OFFLOAD_REVISION_1;
2136 }
2137 vboxNetLwfWinIndicateOffload(pModuleCtx, &OffloadConfig);
2138 Log(("vboxNetLwfWinToggleOffloading: set offloading off\n"));
2139 }
2140 else
2141 {
2142 /* The filter is inactive -- restore offloading configuration. */
2143 if (pModuleCtx->fOffloadConfigValid)
2144 {
2145 vboxNetLwfWinIndicateOffload(pModuleCtx, &pModuleCtx->SavedOffloadConfig);
2146 Log(("vboxNetLwfWinToggleOffloading: restored offloading config\n"));
2147 }
2148 else
2149 DbgPrint("VBoxNetLwf: no saved offload config to restore for %s\n", pModuleCtx->szMiniportName);
2150 }
2151}
2152
2153
2154void vboxNetFltPortOsSetActive(PVBOXNETFLTINS pThis, bool fActive)
2155{
2156 PVBOXNETLWF_MODULE pModuleCtx = (PVBOXNETLWF_MODULE)pThis->u.s.WinIf.hModuleCtx;
2157 LogFlow(("==>vboxNetFltPortOsSetActive: instance=%p module=%p fActive=%RTbool\n", pThis, pModuleCtx, fActive));
2158 if (!pModuleCtx)
2159 {
2160 LogFlow(("<==vboxNetFltPortOsSetActive: pModuleCtx is null\n"));
2161 return;
2162 }
2163
2164 NDIS_STATUS Status = STATUS_SUCCESS;
2165 bool fOldActive = ASMAtomicXchgBool(&pModuleCtx->fActive, fActive);
2166 if (fOldActive != fActive)
2167 {
2168 NdisQueueIoWorkItem(pModuleCtx->hWorkItem, vboxNetLwfWinToggleOffloading, pModuleCtx);
2169 Status = vboxNetLwfWinSetPacketFilter(pModuleCtx, fActive);
2170 LogFlow(("<==vboxNetFltPortOsSetActive: vboxNetLwfWinSetPacketFilter() returned 0x%x\n", Status));
2171 }
2172 else
2173 LogFlow(("<==vboxNetFltPortOsSetActive: no change, remain %sactive\n", fActive ? "":"in"));
2174}
2175
2176int vboxNetFltOsDisconnectIt(PVBOXNETFLTINS pThis)
2177{
2178 LogFlow(("==>vboxNetFltOsDisconnectIt: instance=%p\n", pThis));
2179 LogFlow(("<==vboxNetFltOsDisconnectIt: return 0\n"));
2180 return VINF_SUCCESS;
2181}
2182
2183int vboxNetFltOsConnectIt(PVBOXNETFLTINS pThis)
2184{
2185 LogFlow(("==>vboxNetFltOsConnectIt: instance=%p\n", pThis));
2186 LogFlow(("<==vboxNetFltOsConnectIt: return 0\n"));
2187 return VINF_SUCCESS;
2188}
2189
2190/*
2191 * Uncommenting the following line produces debug log messages on IP address changes,
2192 * including wired interfaces. No actual calls to a switch port are made. This is for
2193 * debug purposes only!
2194 * #define VBOXNETLWFWIN_DEBUGIPADDRNOTIF 1
2195 */
2196static void vboxNetLwfWinIpAddrChangeCallback(IN PVOID pvCtx,
2197 IN PMIB_UNICASTIPADDRESS_ROW pRow,
2198 IN MIB_NOTIFICATION_TYPE enmNotifType)
2199{
2200 PVBOXNETFLTINS pThis = (PVBOXNETFLTINS)pvCtx;
2201 PVBOXNETLWF_MODULE pModule = (PVBOXNETLWF_MODULE)pThis->u.s.WinIf.hModuleCtx;
2202
2203 /* We are only interested in add or remove notifications. */
2204 bool fAdded;
2205 if (enmNotifType == MibAddInstance)
2206 fAdded = true;
2207 else if (enmNotifType == MibDeleteInstance)
2208 fAdded = false;
2209 else
2210 return;
2211
2212 if ( pRow
2213#ifndef VBOXNETLWFWIN_DEBUGIPADDRNOTIF
2214 && pThis->pSwitchPort->pfnNotifyHostAddress
2215#endif /* !VBOXNETLWFWIN_DEBUGIPADDRNOTIF */
2216 )
2217 {
2218 switch (pRow->Address.si_family)
2219 {
2220 case AF_INET:
2221 if ( IN4_IS_ADDR_LINKLOCAL(&pRow->Address.Ipv4.sin_addr)
2222 || pRow->Address.Ipv4.sin_addr.s_addr == IN4ADDR_LOOPBACK)
2223 {
2224 Log(("vboxNetLwfWinIpAddrChangeCallback: ignoring %s address (%RTnaipv4)\n",
2225 pRow->Address.Ipv4.sin_addr.s_addr == IN4ADDR_LOOPBACK ? "loopback" : "link-local",
2226 pRow->Address.Ipv4.sin_addr));
2227 break;
2228 }
2229 Log(("vboxNetLwfWinIpAddrChangeCallback: %s IPv4 addr=%RTnaipv4 on luid=(%u,%u)\n",
2230 fAdded ? "add" : "remove", pRow->Address.Ipv4.sin_addr,
2231 pRow->InterfaceLuid.Info.IfType, pRow->InterfaceLuid.Info.NetLuidIndex));
2232#ifndef VBOXNETLWFWIN_DEBUGIPADDRNOTIF
2233 pThis->pSwitchPort->pfnNotifyHostAddress(pThis->pSwitchPort, fAdded, kIntNetAddrType_IPv4,
2234 &pRow->Address.Ipv4.sin_addr);
2235#endif /* !VBOXNETLWFWIN_DEBUGIPADDRNOTIF */
2236 break;
2237 case AF_INET6:
2238 if (Ipv6AddressScope(pRow->Address.Ipv6.sin6_addr.u.Byte) <= ScopeLevelLink)
2239 {
2240 Log(("vboxNetLwfWinIpAddrChangeCallback: ignoring link-local address (%RTnaipv6)\n",
2241 &pRow->Address.Ipv6.sin6_addr));
2242 break;
2243 }
2244 Log(("vboxNetLwfWinIpAddrChangeCallback: %s IPv6 addr=%RTnaipv6 scope=%d luid=(%u,%u)\n",
2245 fAdded ? "add" : "remove", &pRow->Address.Ipv6.sin6_addr,
2246 Ipv6AddressScope(pRow->Address.Ipv6.sin6_addr.u.Byte),
2247 pRow->InterfaceLuid.Info.IfType, pRow->InterfaceLuid.Info.NetLuidIndex));
2248#ifndef VBOXNETLWFWIN_DEBUGIPADDRNOTIF
2249 pThis->pSwitchPort->pfnNotifyHostAddress(pThis->pSwitchPort, fAdded, kIntNetAddrType_IPv6,
2250 &pRow->Address.Ipv6.sin6_addr);
2251#endif /* !VBOXNETLWFWIN_DEBUGIPADDRNOTIF */
2252 break;
2253 }
2254 }
2255 else
2256 Log(("vboxNetLwfWinIpAddrChangeCallback: pRow=%p pfnNotifyHostAddress=%p\n",
2257 pRow, pThis->pSwitchPort->pfnNotifyHostAddress));
2258}
2259
2260void vboxNetLwfWinRegisterIpAddrNotifier(PVBOXNETFLTINS pThis)
2261{
2262 LogFlow(("==>vboxNetLwfWinRegisterIpAddrNotifier: instance=%p\n", pThis));
2263 if ( pThis->pSwitchPort
2264#ifndef VBOXNETLWFWIN_DEBUGIPADDRNOTIF
2265 && pThis->pSwitchPort->pfnNotifyHostAddress
2266#endif /* !VBOXNETLWFWIN_DEBUGIPADDRNOTIF */
2267 )
2268 {
2269 NETIO_STATUS Status;
2270 /* First we need to go over all host IP addresses and add them via pfnNotifyHostAddress. */
2271 PMIB_UNICASTIPADDRESS_TABLE HostIpAddresses = NULL;
2272 Status = GetUnicastIpAddressTable(AF_UNSPEC, &HostIpAddresses);
2273 if (NETIO_SUCCESS(Status))
2274 {
2275 for (unsigned i = 0; i < HostIpAddresses->NumEntries; i++)
2276 vboxNetLwfWinIpAddrChangeCallback(pThis, &HostIpAddresses->Table[i], MibAddInstance);
2277 }
2278 else
2279 Log(("ERROR! vboxNetLwfWinRegisterIpAddrNotifier: GetUnicastIpAddressTable failed with %x\n", Status));
2280 /* Now we can register a callback function to keep track of address changes. */
2281 Status = NotifyUnicastIpAddressChange(AF_UNSPEC, vboxNetLwfWinIpAddrChangeCallback,
2282 pThis, false, &pThis->u.s.WinIf.hNotifier);
2283 if (NETIO_SUCCESS(Status))
2284 Log(("vboxNetLwfWinRegisterIpAddrNotifier: notifier=%p\n", pThis->u.s.WinIf.hNotifier));
2285 else
2286 Log(("ERROR! vboxNetLwfWinRegisterIpAddrNotifier: NotifyUnicastIpAddressChange failed with %x\n", Status));
2287 }
2288 else
2289 pThis->u.s.WinIf.hNotifier = NULL;
2290 LogFlow(("<==vboxNetLwfWinRegisterIpAddrNotifier\n"));
2291}
2292
2293void vboxNetLwfWinUnregisterIpAddrNotifier(PVBOXNETFLTINS pThis)
2294{
2295 Log(("vboxNetLwfWinUnregisterIpAddrNotifier: notifier=%p\n", pThis->u.s.WinIf.hNotifier));
2296 if (pThis->u.s.WinIf.hNotifier)
2297 CancelMibChangeNotify2(pThis->u.s.WinIf.hNotifier);
2298}
2299
2300void vboxNetFltOsDeleteInstance(PVBOXNETFLTINS pThis)
2301{
2302 PVBOXNETLWF_MODULE pModuleCtx = (PVBOXNETLWF_MODULE)pThis->u.s.WinIf.hModuleCtx;
2303 LogFlow(("==>vboxNetFltOsDeleteInstance: instance=%p module=%p\n", pThis, pModuleCtx));
2304 /* Cancel IP address change notifications */
2305 vboxNetLwfWinUnregisterIpAddrNotifier(pThis);
2306 /* Technically it is possible that the module has already been gone by now. */
2307 if (pModuleCtx)
2308 {
2309 Assert(!pModuleCtx->fActive); /* Deactivation ensures bypass mode */
2310 pModuleCtx->pNetFlt = NULL;
2311 pThis->u.s.WinIf.hModuleCtx = NULL;
2312 }
2313 LogFlow(("<==vboxNetFltOsDeleteInstance\n"));
2314}
2315
2316static void vboxNetLwfWinReportCapabilities(PVBOXNETFLTINS pThis, PVBOXNETLWF_MODULE pModuleCtx)
2317{
2318 if (pThis->pSwitchPort
2319 && vboxNetFltTryRetainBusyNotDisconnected(pThis))
2320 {
2321 pThis->pSwitchPort->pfnReportMacAddress(pThis->pSwitchPort, &pModuleCtx->MacAddr);
2322 pThis->pSwitchPort->pfnReportPromiscuousMode(pThis->pSwitchPort,
2323 vboxNetLwfWinIsPromiscuous(pModuleCtx));
2324 pThis->pSwitchPort->pfnReportGsoCapabilities(pThis->pSwitchPort, 0,
2325 INTNETTRUNKDIR_WIRE | INTNETTRUNKDIR_HOST);
2326 pThis->pSwitchPort->pfnReportNoPreemptDsts(pThis->pSwitchPort, 0 /* none */);
2327 vboxNetFltRelease(pThis, true /*fBusy*/);
2328 }
2329}
2330
2331int vboxNetFltOsInitInstance(PVBOXNETFLTINS pThis, void *pvContext)
2332{
2333 LogFlow(("==>vboxNetFltOsInitInstance: instance=%p context=%p\n", pThis, pvContext));
2334 AssertReturn(pThis, VERR_INVALID_PARAMETER);
2335 Log(("vboxNetFltOsInitInstance: trunk name=%s\n", pThis->szName));
2336 PVBOXNETLWF_MODULE pModuleCtx = NULL;
2337 NdisAcquireSpinLock(&g_VBoxNetLwfGlobals.Lock);
2338 RTListForEach(&g_VBoxNetLwfGlobals.listModules, pModuleCtx, VBOXNETLWF_MODULE, node)
2339 {
2340 DbgPrint("vboxNetFltOsInitInstance: evaluating module, name=%s\n", pModuleCtx->szMiniportName);
2341 if (!RTStrICmp(pThis->szName, pModuleCtx->szMiniportName))
2342 {
2343 NdisReleaseSpinLock(&g_VBoxNetLwfGlobals.Lock);
2344 Log(("vboxNetFltOsInitInstance: found matching module, name=%s\n", pThis->szName));
2345 pThis->u.s.WinIf.hModuleCtx = pModuleCtx;
2346 pModuleCtx->pNetFlt = pThis;
2347 vboxNetLwfWinReportCapabilities(pThis, pModuleCtx);
2348 vboxNetLwfWinRegisterIpAddrNotifier(pThis);
2349 LogFlow(("<==vboxNetFltOsInitInstance: return 0\n"));
2350 return VINF_SUCCESS;
2351 }
2352 }
2353 NdisReleaseSpinLock(&g_VBoxNetLwfGlobals.Lock);
2354 LogFlow(("<==vboxNetFltOsInitInstance: return VERR_INTNET_FLT_IF_NOT_FOUND\n"));
2355 return VERR_INTNET_FLT_IF_NOT_FOUND;
2356}
2357
2358int vboxNetFltOsPreInitInstance(PVBOXNETFLTINS pThis)
2359{
2360 LogFlow(("==>vboxNetFltOsPreInitInstance: instance=%p\n", pThis));
2361 pThis->u.s.WinIf.hModuleCtx = 0;
2362 pThis->u.s.WinIf.hNotifier = NULL;
2363 LogFlow(("<==vboxNetFltOsPreInitInstance: return 0\n"));
2364 return VINF_SUCCESS;
2365}
2366
2367void vboxNetFltPortOsNotifyMacAddress(PVBOXNETFLTINS pThis, void *pvIfData, PCRTMAC pMac)
2368{
2369 LogFlow(("==>vboxNetFltPortOsNotifyMacAddress: instance=%p data=%p mac=%RTmac\n", pThis, pvIfData, pMac));
2370 LogFlow(("<==vboxNetFltPortOsNotifyMacAddress\n"));
2371}
2372
2373int vboxNetFltPortOsConnectInterface(PVBOXNETFLTINS pThis, void *pvIf, void **ppvIfData)
2374{
2375 LogFlow(("==>vboxNetFltPortOsConnectInterface: instance=%p if=%p data=%p\n", pThis, pvIf, ppvIfData));
2376 LogFlow(("<==vboxNetFltPortOsConnectInterface: return 0\n"));
2377 /* Nothing to do */
2378 return VINF_SUCCESS;
2379}
2380
2381int vboxNetFltPortOsDisconnectInterface(PVBOXNETFLTINS pThis, void *pvIfData)
2382{
2383 LogFlow(("==>vboxNetFltPortOsDisconnectInterface: instance=%p data=%p\n", pThis, pvIfData));
2384 LogFlow(("<==vboxNetFltPortOsDisconnectInterface: return 0\n"));
2385 /* Nothing to do */
2386 return VINF_SUCCESS;
2387}
2388
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette