VirtualBox

source: vbox/trunk/src/VBox/Devices/Network/DrvIntNet.cpp@ 60404

Last change on this file since 60404 was 60076, checked in by vboxsync, 8 years ago

IntNet: Unregister all registered statistics counters.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 73.9 KB
Line 
1/* $Id: DrvIntNet.cpp 60076 2016-03-17 13:38:30Z vboxsync $ */
2/** @file
3 * DrvIntNet - Internal network transport driver.
4 */
5
6/*
7 * Copyright (C) 2006-2015 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_INTNET
23#include <VBox/vmm/pdmdrv.h>
24#include <VBox/vmm/pdmnetinline.h>
25#include <VBox/vmm/pdmnetifs.h>
26#include <VBox/vmm/cfgm.h>
27#include <VBox/intnet.h>
28#include <VBox/intnetinline.h>
29#include <VBox/vmm/vmm.h>
30#include <VBox/sup.h>
31#include <VBox/err.h>
32
33#include <VBox/param.h>
34#include <VBox/log.h>
35#include <iprt/asm.h>
36#include <iprt/assert.h>
37#include <iprt/ctype.h>
38#include <iprt/memcache.h>
39#include <iprt/net.h>
40#include <iprt/semaphore.h>
41#include <iprt/string.h>
42#include <iprt/time.h>
43#include <iprt/thread.h>
44#include <iprt/uuid.h>
45#if defined(RT_OS_DARWIN) && defined(IN_RING3)
46# include <iprt/system.h>
47#endif
48
49#include "VBoxDD.h"
50
51
52/*********************************************************************************************************************************
53* Defined Constants And Macros *
54*********************************************************************************************************************************/
55/** Enables the ring-0 part. */
56#define VBOX_WITH_DRVINTNET_IN_R0
57
58
59/*********************************************************************************************************************************
60* Structures and Typedefs *
61*********************************************************************************************************************************/
62/**
63 * The state of the asynchronous thread.
64 */
65typedef enum RECVSTATE
66{
67 /** The thread is suspended. */
68 RECVSTATE_SUSPENDED = 1,
69 /** The thread is running. */
70 RECVSTATE_RUNNING,
71 /** The thread must (/has) terminate. */
72 RECVSTATE_TERMINATE,
73 /** The usual 32-bit type blowup. */
74 RECVSTATE_32BIT_HACK = 0x7fffffff
75} RECVSTATE;
76
77/**
78 * Internal networking driver instance data.
79 *
80 * @implements PDMINETWORKUP
81 */
82typedef struct DRVINTNET
83{
84 /** The network interface. */
85 PDMINETWORKUP INetworkUpR3;
86 /** The network interface. */
87 R3PTRTYPE(PPDMINETWORKDOWN) pIAboveNet;
88 /** The network config interface.
89 * Can (in theory at least) be NULL. */
90 R3PTRTYPE(PPDMINETWORKCONFIG) pIAboveConfigR3;
91 /** Pointer to the driver instance (ring-3). */
92 PPDMDRVINSR3 pDrvInsR3;
93 /** Pointer to the communication buffer (ring-3). */
94 R3PTRTYPE(PINTNETBUF) pBufR3;
95 /** Ring-3 base interface for the ring-0 context. */
96 PDMIBASER0 IBaseR0;
97 /** Ring-3 base interface for the raw-mode context. */
98 PDMIBASERC IBaseRC;
99 RTR3PTR R3PtrAlignment;
100
101 /** The network interface for the ring-0 context. */
102 PDMINETWORKUPR0 INetworkUpR0;
103 /** Pointer to the driver instance (ring-0). */
104 PPDMDRVINSR0 pDrvInsR0;
105 /** Pointer to the communication buffer (ring-0). */
106 R0PTRTYPE(PINTNETBUF) pBufR0;
107
108 /** The network interface for the raw-mode context. */
109 PDMINETWORKUPRC INetworkUpRC;
110 /** Pointer to the driver instance. */
111 PPDMDRVINSRC pDrvInsRC;
112 RTRCPTR RCPtrAlignment;
113
114 /** The transmit lock. */
115 PDMCRITSECT XmitLock;
116 /** Interface handle. */
117 INTNETIFHANDLE hIf;
118 /** The receive thread state. */
119 RECVSTATE volatile enmRecvState;
120 /** The receive thread. */
121 RTTHREAD hRecvThread;
122 /** The event semaphore that the receive thread waits on. */
123 RTSEMEVENT hRecvEvt;
124 /** The transmit thread. */
125 PPDMTHREAD pXmitThread;
126 /** The event semaphore that the transmit thread waits on. */
127 SUPSEMEVENT hXmitEvt;
128 /** The support driver session handle. */
129 PSUPDRVSESSION pSupDrvSession;
130 /** Scatter/gather descriptor cache. */
131 RTMEMCACHE hSgCache;
132 /** Set if the link is down.
133 * When the link is down all incoming packets will be dropped. */
134 bool volatile fLinkDown;
135 /** Set when the xmit thread has been signalled. (atomic) */
136 bool volatile fXmitSignalled;
137 /** Set if the transmit thread the one busy transmitting. */
138 bool volatile fXmitOnXmitThread;
139 /** The xmit thread should process the ring ASAP. */
140 bool fXmitProcessRing;
141 /** Set if data transmission should start immediately and deactivate
142 * as late as possible. */
143 bool fActivateEarlyDeactivateLate;
144 /** Padding. */
145 bool afReserved[HC_ARCH_BITS == 64 ? 3 : 3];
146 /** Scratch space for holding the ring-0 scatter / gather descriptor.
147 * The PDMSCATTERGATHER::fFlags member is used to indicate whether it is in
148 * use or not. Always accessed while owning the XmitLock. */
149 union
150 {
151 PDMSCATTERGATHER Sg;
152 uint8_t padding[8 * sizeof(RTUINTPTR)];
153 } u;
154 /** The network name. */
155 char szNetwork[INTNET_MAX_NETWORK_NAME];
156
157 /** Number of GSO packets sent. */
158 STAMCOUNTER StatSentGso;
159 /** Number of GSO packets received. */
160 STAMCOUNTER StatReceivedGso;
161 /** Number of packets send from ring-0. */
162 STAMCOUNTER StatSentR0;
163 /** The number of times we've had to wake up the xmit thread to continue the
164 * ring-0 job. */
165 STAMCOUNTER StatXmitWakeupR0;
166 /** The number of times we've had to wake up the xmit thread to continue the
167 * ring-3 job. */
168 STAMCOUNTER StatXmitWakeupR3;
169 /** The times the xmit thread has been told to process the ring. */
170 STAMCOUNTER StatXmitProcessRing;
171#ifdef VBOX_WITH_STATISTICS
172 /** Profiling packet transmit runs. */
173 STAMPROFILE StatTransmit;
174 /** Profiling packet receive runs. */
175 STAMPROFILEADV StatReceive;
176#endif /* VBOX_WITH_STATISTICS */
177#ifdef LOG_ENABLED
178 /** The nano ts of the last transfer. */
179 uint64_t u64LastTransferTS;
180 /** The nano ts of the last receive. */
181 uint64_t u64LastReceiveTS;
182#endif
183} DRVINTNET;
184AssertCompileMemberAlignment(DRVINTNET, XmitLock, 8);
185AssertCompileMemberAlignment(DRVINTNET, StatSentGso, 8);
186/** Pointer to instance data of the internal networking driver. */
187typedef DRVINTNET *PDRVINTNET;
188
189/**
190 * Config value to flag translation structure.
191 */
192typedef struct DRVINTNETFLAG
193{
194 /** The value. */
195 const char *pszChoice;
196 /** The corresponding flag. */
197 uint32_t fFlag;
198} DRVINTNETFLAG;
199/** Pointer to a const flag value translation. */
200typedef DRVINTNETFLAG const *PCDRVINTNETFLAG;
201
202
203#ifdef IN_RING3
204
205
206/**
207 * Updates the MAC address on the kernel side.
208 *
209 * @returns VBox status code.
210 * @param pThis The driver instance.
211 */
212static int drvR3IntNetUpdateMacAddress(PDRVINTNET pThis)
213{
214 if (!pThis->pIAboveConfigR3)
215 return VINF_SUCCESS;
216
217 INTNETIFSETMACADDRESSREQ SetMacAddressReq;
218 SetMacAddressReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
219 SetMacAddressReq.Hdr.cbReq = sizeof(SetMacAddressReq);
220 SetMacAddressReq.pSession = NIL_RTR0PTR;
221 SetMacAddressReq.hIf = pThis->hIf;
222 int rc = pThis->pIAboveConfigR3->pfnGetMac(pThis->pIAboveConfigR3, &SetMacAddressReq.Mac);
223 if (RT_SUCCESS(rc))
224 rc = PDMDrvHlpSUPCallVMMR0Ex(pThis->pDrvInsR3, VMMR0_DO_INTNET_IF_SET_MAC_ADDRESS,
225 &SetMacAddressReq, sizeof(SetMacAddressReq));
226
227 Log(("drvR3IntNetUpdateMacAddress: %.*Rhxs rc=%Rrc\n", sizeof(SetMacAddressReq.Mac), &SetMacAddressReq.Mac, rc));
228 return rc;
229}
230
231
232/**
233 * Sets the kernel interface active or inactive.
234 *
235 * Worker for poweron, poweroff, suspend and resume.
236 *
237 * @returns VBox status code.
238 * @param pThis The driver instance.
239 * @param fActive The new state.
240 */
241static int drvR3IntNetSetActive(PDRVINTNET pThis, bool fActive)
242{
243 if (!pThis->pIAboveConfigR3)
244 return VINF_SUCCESS;
245
246 INTNETIFSETACTIVEREQ SetActiveReq;
247 SetActiveReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
248 SetActiveReq.Hdr.cbReq = sizeof(SetActiveReq);
249 SetActiveReq.pSession = NIL_RTR0PTR;
250 SetActiveReq.hIf = pThis->hIf;
251 SetActiveReq.fActive = fActive;
252 int rc = PDMDrvHlpSUPCallVMMR0Ex(pThis->pDrvInsR3, VMMR0_DO_INTNET_IF_SET_ACTIVE,
253 &SetActiveReq, sizeof(SetActiveReq));
254
255 Log(("drvR3IntNetSetActive: fActive=%d rc=%Rrc\n", fActive, rc));
256 AssertRC(rc);
257 return rc;
258}
259
260#endif /* IN_RING3 */
261
262/* -=-=-=-=- PDMINETWORKUP -=-=-=-=- */
263
264/**
265 * Helper for signalling the xmit thread.
266 *
267 * @returns VERR_TRY_AGAIN (convenience).
268 * @param pThis The instance data..
269 */
270DECLINLINE(int) drvIntNetSignalXmit(PDRVINTNET pThis)
271{
272 /// @todo if (!ASMAtomicXchgBool(&pThis->fXmitSignalled, true)) - needs careful optimizing.
273 {
274 int rc = SUPSemEventSignal(pThis->pSupDrvSession, pThis->hXmitEvt);
275 AssertRC(rc);
276 STAM_REL_COUNTER_INC(&pThis->CTX_SUFF(StatXmitWakeup));
277 }
278 return VERR_TRY_AGAIN;
279}
280
281
282/**
283 * Helper for processing the ring-0 consumer side of the xmit ring.
284 *
285 * The caller MUST own the xmit lock.
286 *
287 * @returns Status code from IntNetR0IfSend, except for VERR_TRY_AGAIN.
288 * @param pThis The instance data..
289 */
290DECLINLINE(int) drvIntNetProcessXmit(PDRVINTNET pThis)
291{
292 Assert(PDMCritSectIsOwner(&pThis->XmitLock));
293
294#ifdef IN_RING3
295 INTNETIFSENDREQ SendReq;
296 SendReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
297 SendReq.Hdr.cbReq = sizeof(SendReq);
298 SendReq.pSession = NIL_RTR0PTR;
299 SendReq.hIf = pThis->hIf;
300 int rc = PDMDrvHlpSUPCallVMMR0Ex(pThis->pDrvInsR3, VMMR0_DO_INTNET_IF_SEND, &SendReq, sizeof(SendReq));
301#else
302 int rc = IntNetR0IfSend(pThis->hIf, pThis->pSupDrvSession);
303 if (rc == VERR_TRY_AGAIN)
304 {
305 ASMAtomicUoWriteBool(&pThis->fXmitProcessRing, true);
306 drvIntNetSignalXmit(pThis);
307 rc = VINF_SUCCESS;
308 }
309#endif
310 return rc;
311}
312
313
314
315/**
316 * @interface_method_impl{PDMINETWORKUP,pfnBeginXmit}
317 */
318PDMBOTHCBDECL(int) drvIntNetUp_BeginXmit(PPDMINETWORKUP pInterface, bool fOnWorkerThread)
319{
320 PDRVINTNET pThis = RT_FROM_MEMBER(pInterface, DRVINTNET, CTX_SUFF(INetworkUp));
321#ifndef IN_RING3
322 Assert(!fOnWorkerThread);
323#endif
324
325 int rc = PDMCritSectTryEnter(&pThis->XmitLock);
326 if (RT_SUCCESS(rc))
327 {
328 if (fOnWorkerThread)
329 {
330 ASMAtomicUoWriteBool(&pThis->fXmitOnXmitThread, true);
331 ASMAtomicWriteBool(&pThis->fXmitSignalled, false);
332 }
333 }
334 else if (rc == VERR_SEM_BUSY)
335 {
336 /** @todo Does this actually make sense if the other dude is an EMT and so
337 * forth? I seriously think this is ring-0 only...
338 * We might end up waking up the xmit thread unnecessarily here, even when in
339 * ring-0... This needs some more thought and optimizations when the ring-0 bits
340 * are working. */
341#ifdef IN_RING3
342 if ( !fOnWorkerThread
343 /*&& !ASMAtomicUoReadBool(&pThis->fXmitOnXmitThread)
344 && ASMAtomicCmpXchgBool(&pThis->fXmitSignalled, true, false)*/)
345 {
346 rc = SUPSemEventSignal(pThis->pSupDrvSession, pThis->hXmitEvt);
347 AssertRC(rc);
348 }
349 rc = VERR_TRY_AGAIN;
350#else /* IN_RING0 */
351 rc = drvIntNetSignalXmit(pThis);
352#endif /* IN_RING0 */
353 }
354 return rc;
355}
356
357
358/**
359 * @interface_method_impl{PDMINETWORKUP,pfnAllocBuf}
360 */
361PDMBOTHCBDECL(int) drvIntNetUp_AllocBuf(PPDMINETWORKUP pInterface, size_t cbMin,
362 PCPDMNETWORKGSO pGso, PPPDMSCATTERGATHER ppSgBuf)
363{
364 PDRVINTNET pThis = RT_FROM_MEMBER(pInterface, DRVINTNET, CTX_SUFF(INetworkUp));
365 int rc = VINF_SUCCESS;
366 Assert(cbMin < UINT32_MAX / 2);
367 Assert(PDMCritSectIsOwner(&pThis->XmitLock));
368
369 /*
370 * Allocate a S/G descriptor.
371 * This shouldn't normally fail as the NICs usually won't allocate more
372 * than one buffer at a time and the SG gets freed on sending.
373 */
374#ifdef IN_RING3
375 PPDMSCATTERGATHER pSgBuf = (PPDMSCATTERGATHER)RTMemCacheAlloc(pThis->hSgCache);
376 if (!pSgBuf)
377 return VERR_NO_MEMORY;
378#else
379 PPDMSCATTERGATHER pSgBuf = &pThis->u.Sg;
380 if (RT_UNLIKELY(pSgBuf->fFlags != 0))
381 return drvIntNetSignalXmit(pThis);
382#endif
383
384 /*
385 * Allocate room in the ring buffer.
386 *
387 * In ring-3 we may have to process the xmit ring before there is
388 * sufficient buffer space since we might have stacked up a few frames to the
389 * trunk while in ring-0. (There is not point of doing this in ring-0.)
390 */
391 PINTNETHDR pHdr = NULL; /* gcc silliness */
392 if (pGso)
393 rc = IntNetRingAllocateGsoFrame(&pThis->CTX_SUFF(pBuf)->Send, (uint32_t)cbMin, pGso,
394 &pHdr, &pSgBuf->aSegs[0].pvSeg);
395 else
396 rc = IntNetRingAllocateFrame(&pThis->CTX_SUFF(pBuf)->Send, (uint32_t)cbMin,
397 &pHdr, &pSgBuf->aSegs[0].pvSeg);
398#ifdef IN_RING3
399 if ( RT_FAILURE(rc)
400 && pThis->CTX_SUFF(pBuf)->cbSend >= cbMin * 2 + sizeof(INTNETHDR))
401 {
402 drvIntNetProcessXmit(pThis);
403 if (pGso)
404 rc = IntNetRingAllocateGsoFrame(&pThis->CTX_SUFF(pBuf)->Send, (uint32_t)cbMin, pGso,
405 &pHdr, &pSgBuf->aSegs[0].pvSeg);
406 else
407 rc = IntNetRingAllocateFrame(&pThis->CTX_SUFF(pBuf)->Send, (uint32_t)cbMin,
408 &pHdr, &pSgBuf->aSegs[0].pvSeg);
409 }
410#endif
411 if (RT_SUCCESS(rc))
412 {
413 /*
414 * Set up the S/G descriptor and return successfully.
415 */
416 pSgBuf->fFlags = PDMSCATTERGATHER_FLAGS_MAGIC | PDMSCATTERGATHER_FLAGS_OWNER_1;
417 pSgBuf->cbUsed = 0;
418 pSgBuf->cbAvailable = cbMin;
419 pSgBuf->pvAllocator = pHdr;
420 pSgBuf->pvUser = pGso ? (PPDMNETWORKGSO)pSgBuf->aSegs[0].pvSeg - 1 : NULL;
421 pSgBuf->cSegs = 1;
422 pSgBuf->aSegs[0].cbSeg = cbMin;
423
424 *ppSgBuf = pSgBuf;
425 return VINF_SUCCESS;
426 }
427
428#ifdef IN_RING3
429 /*
430 * If the above fails, then we're really out of space. There are nobody
431 * competing with us here because of the xmit lock.
432 */
433 rc = VERR_NO_MEMORY;
434 RTMemCacheFree(pThis->hSgCache, pSgBuf);
435
436#else /* IN_RING0 */
437 /*
438 * If the request is reasonable, kick the xmit thread and tell it to
439 * process the xmit ring ASAP.
440 */
441 if (pThis->CTX_SUFF(pBuf)->cbSend >= cbMin * 2 + sizeof(INTNETHDR))
442 {
443 pThis->fXmitProcessRing = true;
444 rc = drvIntNetSignalXmit(pThis);
445 }
446 else
447 rc = VERR_NO_MEMORY;
448 pSgBuf->fFlags = 0;
449#endif /* IN_RING0 */
450 return rc;
451}
452
453
454/**
455 * @interface_method_impl{PDMINETWORKUP,pfnFreeBuf}
456 */
457PDMBOTHCBDECL(int) drvIntNetUp_FreeBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf)
458{
459 PDRVINTNET pThis = RT_FROM_MEMBER(pInterface, DRVINTNET, CTX_SUFF(INetworkUp));
460 PINTNETHDR pHdr = (PINTNETHDR)pSgBuf->pvAllocator;
461#ifdef IN_RING0
462 Assert(pSgBuf == &pThis->u.Sg);
463#endif
464 Assert(pSgBuf->fFlags == (PDMSCATTERGATHER_FLAGS_MAGIC | PDMSCATTERGATHER_FLAGS_OWNER_1));
465 Assert(pSgBuf->cbUsed <= pSgBuf->cbAvailable);
466 Assert( pHdr->u8Type == INTNETHDR_TYPE_FRAME
467 || pHdr->u8Type == INTNETHDR_TYPE_GSO);
468 Assert(PDMCritSectIsOwner(&pThis->XmitLock));
469
470 /** @todo LATER: try unalloc the frame. */
471 pHdr->u8Type = INTNETHDR_TYPE_PADDING;
472 IntNetRingCommitFrame(&pThis->CTX_SUFF(pBuf)->Send, pHdr);
473
474#ifdef IN_RING3
475 RTMemCacheFree(pThis->hSgCache, pSgBuf);
476#else
477 pSgBuf->fFlags = 0;
478#endif
479 return VINF_SUCCESS;
480}
481
482
483/**
484 * @interface_method_impl{PDMINETWORKUP,pfnSendBuf}
485 */
486PDMBOTHCBDECL(int) drvIntNetUp_SendBuf(PPDMINETWORKUP pInterface, PPDMSCATTERGATHER pSgBuf, bool fOnWorkerThread)
487{
488 PDRVINTNET pThis = RT_FROM_MEMBER(pInterface, DRVINTNET, CTX_SUFF(INetworkUp));
489 STAM_PROFILE_START(&pThis->StatTransmit, a);
490
491 AssertPtr(pSgBuf);
492 Assert(pSgBuf->fFlags == (PDMSCATTERGATHER_FLAGS_MAGIC | PDMSCATTERGATHER_FLAGS_OWNER_1));
493 Assert(pSgBuf->cbUsed <= pSgBuf->cbAvailable);
494 Assert(PDMCritSectIsOwner(&pThis->XmitLock));
495
496 if (pSgBuf->pvUser)
497 STAM_COUNTER_INC(&pThis->StatSentGso);
498
499 /* Set an FTM checkpoint as this operation changes the state permanently. */
500 PDMDrvHlpFTSetCheckpoint(pThis->CTX_SUFF(pDrvIns), FTMCHECKPOINTTYPE_NETWORK);
501
502 /*
503 * Commit the frame and push it thru the switch.
504 */
505 PINTNETHDR pHdr = (PINTNETHDR)pSgBuf->pvAllocator;
506 IntNetRingCommitFrameEx(&pThis->CTX_SUFF(pBuf)->Send, pHdr, pSgBuf->cbUsed);
507 int rc = drvIntNetProcessXmit(pThis);
508 STAM_PROFILE_STOP(&pThis->StatTransmit, a);
509
510 /*
511 * Free the descriptor and return.
512 */
513#ifdef IN_RING3
514 RTMemCacheFree(pThis->hSgCache, pSgBuf);
515#else
516 STAM_REL_COUNTER_INC(&pThis->StatSentR0);
517 pSgBuf->fFlags = 0;
518#endif
519 return rc;
520}
521
522
523/**
524 * @interface_method_impl{PDMINETWORKUP,pfnEndXmit}
525 */
526PDMBOTHCBDECL(void) drvIntNetUp_EndXmit(PPDMINETWORKUP pInterface)
527{
528 PDRVINTNET pThis = RT_FROM_MEMBER(pInterface, DRVINTNET, CTX_SUFF(INetworkUp));
529 ASMAtomicUoWriteBool(&pThis->fXmitOnXmitThread, false);
530 PDMCritSectLeave(&pThis->XmitLock);
531}
532
533
534/**
535 * @interface_method_impl{PDMINETWORKUP,pfnSetPromiscuousMode}
536 */
537PDMBOTHCBDECL(void) drvIntNetUp_SetPromiscuousMode(PPDMINETWORKUP pInterface, bool fPromiscuous)
538{
539 PDRVINTNET pThis = RT_FROM_MEMBER(pInterface, DRVINTNET, CTX_SUFF(INetworkUp));
540
541#ifdef IN_RING3
542 INTNETIFSETPROMISCUOUSMODEREQ Req;
543 Req.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
544 Req.Hdr.cbReq = sizeof(Req);
545 Req.pSession = NIL_RTR0PTR;
546 Req.hIf = pThis->hIf;
547 Req.fPromiscuous = fPromiscuous;
548 int rc = PDMDrvHlpSUPCallVMMR0Ex(pThis->pDrvInsR3, VMMR0_DO_INTNET_IF_SET_PROMISCUOUS_MODE, &Req, sizeof(Req));
549#else /* IN_RING0 */
550 int rc = IntNetR0IfSetPromiscuousMode(pThis->hIf, pThis->pSupDrvSession, fPromiscuous);
551#endif /* IN_RING0 */
552
553 LogFlow(("drvIntNetUp_SetPromiscuousMode: fPromiscuous=%RTbool\n", fPromiscuous));
554 AssertRC(rc);
555}
556
557#ifdef IN_RING3
558
559/**
560 * @interface_method_impl{PDMINETWORKUP,pfnNotifyLinkChanged}
561 */
562static DECLCALLBACK(void) drvR3IntNetUp_NotifyLinkChanged(PPDMINETWORKUP pInterface, PDMNETWORKLINKSTATE enmLinkState)
563{
564 PDRVINTNET pThis = RT_FROM_MEMBER(pInterface, DRVINTNET, CTX_SUFF(INetworkUp));
565 bool fLinkDown;
566 switch (enmLinkState)
567 {
568 case PDMNETWORKLINKSTATE_DOWN:
569 case PDMNETWORKLINKSTATE_DOWN_RESUME:
570 fLinkDown = true;
571 break;
572 default:
573 AssertMsgFailed(("enmLinkState=%d\n", enmLinkState));
574 case PDMNETWORKLINKSTATE_UP:
575 fLinkDown = false;
576 break;
577 }
578 LogFlow(("drvR3IntNetUp_NotifyLinkChanged: enmLinkState=%d %d->%d\n", enmLinkState, pThis->fLinkDown, fLinkDown));
579 ASMAtomicXchgSize(&pThis->fLinkDown, fLinkDown);
580}
581
582
583/* -=-=-=-=- Transmit Thread -=-=-=-=- */
584
585/**
586 * Async I/O thread for deferred packet transmission.
587 *
588 * @returns VBox status code. Returning failure will naturally terminate the thread.
589 * @param pDrvIns The internal networking driver instance.
590 * @param pThread The thread.
591 */
592static DECLCALLBACK(int) drvR3IntNetXmitThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
593{
594 PDRVINTNET pThis = PDMINS_2_DATA(pDrvIns, PDRVINTNET);
595
596 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
597 {
598 /*
599 * Transmit any pending packets.
600 */
601 /** @todo Optimize this. We shouldn't call pfnXmitPending unless asked for.
602 * Also there is no need to call drvIntNetProcessXmit if we also
603 * called pfnXmitPending and send one or more frames. */
604 if (ASMAtomicXchgBool(&pThis->fXmitProcessRing, false))
605 {
606 STAM_REL_COUNTER_INC(&pThis->StatXmitProcessRing);
607 PDMCritSectEnter(&pThis->XmitLock, VERR_IGNORED);
608 drvIntNetProcessXmit(pThis);
609 PDMCritSectLeave(&pThis->XmitLock);
610 }
611
612 pThis->pIAboveNet->pfnXmitPending(pThis->pIAboveNet);
613
614 if (ASMAtomicXchgBool(&pThis->fXmitProcessRing, false))
615 {
616 STAM_REL_COUNTER_INC(&pThis->StatXmitProcessRing);
617 PDMCritSectEnter(&pThis->XmitLock, VERR_IGNORED);
618 drvIntNetProcessXmit(pThis);
619 PDMCritSectLeave(&pThis->XmitLock);
620 }
621
622 /*
623 * Block until we've got something to send or is supposed
624 * to leave the running state.
625 */
626 int rc = SUPSemEventWaitNoResume(pThis->pSupDrvSession, pThis->hXmitEvt, RT_INDEFINITE_WAIT);
627 AssertLogRelMsgReturn(RT_SUCCESS(rc) || rc == VERR_INTERRUPTED, ("%Rrc\n", rc), rc);
628 if (RT_UNLIKELY(pThread->enmState != PDMTHREADSTATE_RUNNING))
629 break;
630
631 }
632
633 /* The thread is being initialized, suspended or terminated. */
634 return VINF_SUCCESS;
635}
636
637
638/**
639 * @copydoc FNPDMTHREADWAKEUPDRV
640 */
641static DECLCALLBACK(int) drvR3IntNetXmitWakeUp(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
642{
643 PDRVINTNET pThis = PDMINS_2_DATA(pDrvIns, PDRVINTNET);
644 return SUPSemEventSignal(pThis->pSupDrvSession, pThis->hXmitEvt);
645}
646
647
648/* -=-=-=-=- Receive Thread -=-=-=-=- */
649
650/**
651 * Wait for space to become available up the driver/device chain.
652 *
653 * @returns VINF_SUCCESS if space is available.
654 * @returns VERR_STATE_CHANGED if the state changed.
655 * @returns VBox status code on other errors.
656 * @param pThis Pointer to the instance data.
657 */
658static int drvR3IntNetRecvWaitForSpace(PDRVINTNET pThis)
659{
660 LogFlow(("drvR3IntNetRecvWaitForSpace:\n"));
661 STAM_PROFILE_ADV_STOP(&pThis->StatReceive, a);
662 int rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, RT_INDEFINITE_WAIT);
663 STAM_PROFILE_ADV_START(&pThis->StatReceive, a);
664 LogFlow(("drvR3IntNetRecvWaitForSpace: returns %Rrc\n", rc));
665 return rc;
666}
667
668
669/**
670 * Executes async I/O (RUNNING mode).
671 *
672 * @returns VERR_STATE_CHANGED if the state changed.
673 * @returns Appropriate VBox status code (error) on fatal error.
674 * @param pThis The driver instance data.
675 */
676static int drvR3IntNetRecvRun(PDRVINTNET pThis)
677{
678 PPDMDRVINS pDrvIns = pThis->pDrvInsR3;
679 LogFlow(("drvR3IntNetRecvRun: pThis=%p\n", pThis));
680
681 /*
682 * The running loop - processing received data and waiting for more to arrive.
683 */
684 STAM_PROFILE_ADV_START(&pThis->StatReceive, a);
685 PINTNETBUF pBuf = pThis->CTX_SUFF(pBuf);
686 PINTNETRINGBUF pRingBuf = &pBuf->Recv;
687 for (;;)
688 {
689 /*
690 * Process the receive buffer.
691 */
692 PINTNETHDR pHdr;
693 while ((pHdr = IntNetRingGetNextFrameToRead(pRingBuf)) != NULL)
694 {
695 /*
696 * Check the state and then inspect the packet.
697 */
698 if (pThis->enmRecvState != RECVSTATE_RUNNING)
699 {
700 STAM_PROFILE_ADV_STOP(&pThis->StatReceive, a);
701 LogFlow(("drvR3IntNetRecvRun: returns VERR_STATE_CHANGED (state changed - #0)\n"));
702 return VERR_STATE_CHANGED;
703 }
704
705 Log2(("pHdr=%p offRead=%#x: %.8Rhxs\n", pHdr, pRingBuf->offReadX, pHdr));
706 uint8_t u8Type = pHdr->u8Type;
707 if ( ( u8Type == INTNETHDR_TYPE_FRAME
708 || u8Type == INTNETHDR_TYPE_GSO)
709 && !pThis->fLinkDown)
710 {
711 /*
712 * Check if there is room for the frame and pass it up.
713 */
714 size_t cbFrame = pHdr->cbFrame;
715 int rc = pThis->pIAboveNet->pfnWaitReceiveAvail(pThis->pIAboveNet, 0);
716 if (rc == VINF_SUCCESS)
717 {
718 if (u8Type == INTNETHDR_TYPE_FRAME)
719 {
720 /*
721 * Normal frame.
722 */
723#ifdef LOG_ENABLED
724 if (LogIsEnabled())
725 {
726 uint64_t u64Now = RTTimeProgramNanoTS();
727 LogFlow(("drvR3IntNetRecvRun: %-4d bytes at %llu ns deltas: r=%llu t=%llu\n",
728 cbFrame, u64Now, u64Now - pThis->u64LastReceiveTS, u64Now - pThis->u64LastTransferTS));
729 pThis->u64LastReceiveTS = u64Now;
730 Log2(("drvR3IntNetRecvRun: cbFrame=%#x\n"
731 "%.*Rhxd\n",
732 cbFrame, cbFrame, IntNetHdrGetFramePtr(pHdr, pBuf)));
733 }
734#endif
735 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, IntNetHdrGetFramePtr(pHdr, pBuf), cbFrame);
736 AssertRC(rc);
737
738 /* skip to the next frame. */
739 IntNetRingSkipFrame(pRingBuf);
740 }
741 else
742 {
743 /*
744 * Generic segment offload frame (INTNETHDR_TYPE_GSO).
745 */
746 STAM_COUNTER_INC(&pThis->StatReceivedGso);
747 PCPDMNETWORKGSO pGso = IntNetHdrGetGsoContext(pHdr, pBuf);
748 if (PDMNetGsoIsValid(pGso, cbFrame, cbFrame - sizeof(PDMNETWORKGSO)))
749 {
750 if (!pThis->pIAboveNet->pfnReceiveGso ||
751 RT_FAILURE(pThis->pIAboveNet->pfnReceiveGso(pThis->pIAboveNet,
752 (uint8_t *)(pGso + 1),
753 pHdr->cbFrame - sizeof(PDMNETWORKGSO),
754 pGso)))
755 {
756 /*
757 *
758 * This is where we do the offloading since this NIC
759 * does not support large receive offload (LRO).
760 */
761 cbFrame -= sizeof(PDMNETWORKGSO);
762
763 uint8_t abHdrScratch[256];
764 uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso, cbFrame);
765#ifdef LOG_ENABLED
766 if (LogIsEnabled())
767 {
768 uint64_t u64Now = RTTimeProgramNanoTS();
769 LogFlow(("drvR3IntNetRecvRun: %-4d bytes at %llu ns deltas: r=%llu t=%llu; GSO - %u segs\n",
770 cbFrame, u64Now, u64Now - pThis->u64LastReceiveTS, u64Now - pThis->u64LastTransferTS, cSegs));
771 pThis->u64LastReceiveTS = u64Now;
772 Log2(("drvR3IntNetRecvRun: cbFrame=%#x type=%d cbHdrsTotal=%#x cbHdrsSeg=%#x Hdr1=%#x Hdr2=%#x MMS=%#x\n"
773 "%.*Rhxd\n",
774 cbFrame, pGso->u8Type, pGso->cbHdrsTotal, pGso->cbHdrsSeg, pGso->offHdr1, pGso->offHdr2, pGso->cbMaxSeg,
775 cbFrame - sizeof(*pGso), pGso + 1));
776 }
777#endif
778 for (size_t iSeg = 0; iSeg < cSegs; iSeg++)
779 {
780 uint32_t cbSegFrame;
781 void *pvSegFrame = PDMNetGsoCarveSegmentQD(pGso, (uint8_t *)(pGso + 1), cbFrame, abHdrScratch,
782 iSeg, cSegs, &cbSegFrame);
783 rc = drvR3IntNetRecvWaitForSpace(pThis);
784 if (RT_FAILURE(rc))
785 {
786 Log(("drvR3IntNetRecvRun: drvR3IntNetRecvWaitForSpace -> %Rrc; iSeg=%u cSegs=%u\n", rc, iSeg, cSegs));
787 break; /* we drop the rest. */
788 }
789 rc = pThis->pIAboveNet->pfnReceive(pThis->pIAboveNet, pvSegFrame, cbSegFrame);
790 AssertRC(rc);
791 }
792 }
793 }
794 else
795 {
796 AssertMsgFailed(("cbFrame=%#x type=%d cbHdrsTotal=%#x cbHdrsSeg=%#x Hdr1=%#x Hdr2=%#x MMS=%#x\n",
797 cbFrame, pGso->u8Type, pGso->cbHdrsTotal, pGso->cbHdrsSeg, pGso->offHdr1, pGso->offHdr2, pGso->cbMaxSeg));
798 STAM_REL_COUNTER_INC(&pBuf->cStatBadFrames);
799 }
800
801 IntNetRingSkipFrame(pRingBuf);
802 }
803 }
804 else
805 {
806 /*
807 * Wait for sufficient space to become available and then retry.
808 */
809 rc = drvR3IntNetRecvWaitForSpace(pThis);
810 if (RT_FAILURE(rc))
811 {
812 if (rc == VERR_INTERRUPTED)
813 {
814 /*
815 * NIC is going down, likely because the VM is being reset. Skip the frame.
816 */
817 AssertMsg(IntNetIsValidFrameType(pHdr->u8Type), ("Unknown frame type %RX16! offRead=%#x\n", pHdr->u8Type, pRingBuf->offReadX));
818 IntNetRingSkipFrame(pRingBuf);
819 }
820 else
821 {
822 STAM_PROFILE_ADV_STOP(&pThis->StatReceive, a);
823 LogFlow(("drvR3IntNetRecvRun: returns %Rrc (wait-for-space)\n", rc));
824 return rc;
825 }
826 }
827 }
828 }
829 else
830 {
831 /*
832 * Link down or unknown frame - skip to the next frame.
833 */
834 AssertMsg(IntNetIsValidFrameType(pHdr->u8Type), ("Unknown frame type %RX16! offRead=%#x\n", pHdr->u8Type, pRingBuf->offReadX));
835 IntNetRingSkipFrame(pRingBuf);
836 STAM_REL_COUNTER_INC(&pBuf->cStatBadFrames);
837 }
838 } /* while more received data */
839
840 /*
841 * Wait for data, checking the state before we block.
842 */
843 if (pThis->enmRecvState != RECVSTATE_RUNNING)
844 {
845 STAM_PROFILE_ADV_STOP(&pThis->StatReceive, a);
846 LogFlow(("drvR3IntNetRecvRun: returns VINF_SUCCESS (state changed - #1)\n"));
847 return VERR_STATE_CHANGED;
848 }
849 INTNETIFWAITREQ WaitReq;
850 WaitReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
851 WaitReq.Hdr.cbReq = sizeof(WaitReq);
852 WaitReq.pSession = NIL_RTR0PTR;
853 WaitReq.hIf = pThis->hIf;
854 WaitReq.cMillies = 30000; /* 30s - don't wait forever, timeout now and then. */
855 STAM_PROFILE_ADV_STOP(&pThis->StatReceive, a);
856 int rc = PDMDrvHlpSUPCallVMMR0Ex(pDrvIns, VMMR0_DO_INTNET_IF_WAIT, &WaitReq, sizeof(WaitReq));
857 if ( RT_FAILURE(rc)
858 && rc != VERR_TIMEOUT
859 && rc != VERR_INTERRUPTED)
860 {
861 LogFlow(("drvR3IntNetRecvRun: returns %Rrc\n", rc));
862 return rc;
863 }
864 STAM_PROFILE_ADV_START(&pThis->StatReceive, a);
865 }
866}
867
868
869/**
870 * Asynchronous I/O thread for handling receive.
871 *
872 * @returns VINF_SUCCESS (ignored).
873 * @param ThreadSelf Thread handle.
874 * @param pvUser Pointer to a DRVINTNET structure.
875 */
876static DECLCALLBACK(int) drvR3IntNetRecvThread(RTTHREAD ThreadSelf, void *pvUser)
877{
878 PDRVINTNET pThis = (PDRVINTNET)pvUser;
879 LogFlow(("drvR3IntNetRecvThread: pThis=%p\n", pThis));
880 STAM_PROFILE_ADV_START(&pThis->StatReceive, a);
881
882 /*
883 * The main loop - acting on state.
884 */
885 for (;;)
886 {
887 RECVSTATE enmRecvState = pThis->enmRecvState;
888 switch (enmRecvState)
889 {
890 case RECVSTATE_SUSPENDED:
891 {
892 int rc = RTSemEventWait(pThis->hRecvEvt, 30000);
893 if ( RT_FAILURE(rc)
894 && rc != VERR_TIMEOUT)
895 {
896 LogFlow(("drvR3IntNetRecvThread: returns %Rrc\n", rc));
897 return rc;
898 }
899 break;
900 }
901
902 case RECVSTATE_RUNNING:
903 {
904 int rc = drvR3IntNetRecvRun(pThis);
905 if ( rc != VERR_STATE_CHANGED
906 && RT_FAILURE(rc))
907 {
908 LogFlow(("drvR3IntNetRecvThread: returns %Rrc\n", rc));
909 return rc;
910 }
911 break;
912 }
913
914 default:
915 AssertMsgFailed(("Invalid state %d\n", enmRecvState));
916 case RECVSTATE_TERMINATE:
917 LogFlow(("drvR3IntNetRecvThread: returns VINF_SUCCESS\n"));
918 return VINF_SUCCESS;
919 }
920 }
921}
922
923
924/* -=-=-=-=- PDMIBASERC -=-=-=-=- */
925
926/**
927 * @interface_method_impl{PDMIBASERC,pfnQueryInterface}
928 */
929static DECLCALLBACK(RTRCPTR) drvR3IntNetIBaseRC_QueryInterface(PPDMIBASERC pInterface, const char *pszIID)
930{
931 PDRVINTNET pThis = RT_FROM_MEMBER(pInterface, DRVINTNET, IBaseRC);
932
933#if 0
934 PDMIBASERC_RETURN_INTERFACE(pThis->pDrvInsR3, pszIID, PDMINETWORKUP, &pThis->INetworkUpRC);
935#endif
936 return NIL_RTRCPTR;
937}
938
939
940/* -=-=-=-=- PDMIBASER0 -=-=-=-=- */
941
942/**
943 * @interface_method_impl{PDMIBASER0,pfnQueryInterface}
944 */
945static DECLCALLBACK(RTR0PTR) drvR3IntNetIBaseR0_QueryInterface(PPDMIBASER0 pInterface, const char *pszIID)
946{
947 PDRVINTNET pThis = RT_FROM_MEMBER(pInterface, DRVINTNET, IBaseR0);
948#ifdef VBOX_WITH_DRVINTNET_IN_R0
949 PDMIBASER0_RETURN_INTERFACE(pThis->pDrvInsR3, pszIID, PDMINETWORKUP, &pThis->INetworkUpR0);
950#endif
951 return NIL_RTR0PTR;
952}
953
954
955/* -=-=-=-=- PDMIBASE -=-=-=-=- */
956
957/**
958 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
959 */
960static DECLCALLBACK(void *) drvR3IntNetIBase_QueryInterface(PPDMIBASE pInterface, const char *pszIID)
961{
962 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
963 PDRVINTNET pThis = PDMINS_2_DATA(pDrvIns, PDRVINTNET);
964
965 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
966 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASER0, &pThis->IBaseR0);
967 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASERC, &pThis->IBaseRC);
968 PDMIBASE_RETURN_INTERFACE(pszIID, PDMINETWORKUP, &pThis->INetworkUpR3);
969 return NULL;
970}
971
972
973/* -=-=-=-=- PDMDRVREG -=-=-=-=- */
974
975/**
976 * Power Off notification.
977 *
978 * @param pDrvIns The driver instance.
979 */
980static DECLCALLBACK(void) drvR3IntNetPowerOff(PPDMDRVINS pDrvIns)
981{
982 LogFlow(("drvR3IntNetPowerOff\n"));
983 PDRVINTNET pThis = PDMINS_2_DATA(pDrvIns, PDRVINTNET);
984 if (!pThis->fActivateEarlyDeactivateLate)
985 {
986 ASMAtomicXchgSize(&pThis->enmRecvState, RECVSTATE_SUSPENDED);
987 drvR3IntNetSetActive(pThis, false /* fActive */);
988 }
989}
990
991
992/**
993 * drvR3IntNetResume helper.
994 */
995static int drvR3IntNetResumeSend(PDRVINTNET pThis, const void *pvBuf, size_t cb)
996{
997 /*
998 * Add the frame to the send buffer and push it onto the network.
999 */
1000 int rc = IntNetRingWriteFrame(&pThis->pBufR3->Send, pvBuf, (uint32_t)cb);
1001 if ( rc == VERR_BUFFER_OVERFLOW
1002 && pThis->pBufR3->cbSend < cb)
1003 {
1004 INTNETIFSENDREQ SendReq;
1005 SendReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
1006 SendReq.Hdr.cbReq = sizeof(SendReq);
1007 SendReq.pSession = NIL_RTR0PTR;
1008 SendReq.hIf = pThis->hIf;
1009 PDMDrvHlpSUPCallVMMR0Ex(pThis->pDrvInsR3, VMMR0_DO_INTNET_IF_SEND, &SendReq, sizeof(SendReq));
1010
1011 rc = IntNetRingWriteFrame(&pThis->pBufR3->Send, pvBuf, (uint32_t)cb);
1012 }
1013
1014 if (RT_SUCCESS(rc))
1015 {
1016 INTNETIFSENDREQ SendReq;
1017 SendReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
1018 SendReq.Hdr.cbReq = sizeof(SendReq);
1019 SendReq.pSession = NIL_RTR0PTR;
1020 SendReq.hIf = pThis->hIf;
1021 rc = PDMDrvHlpSUPCallVMMR0Ex(pThis->pDrvInsR3, VMMR0_DO_INTNET_IF_SEND, &SendReq, sizeof(SendReq));
1022 }
1023
1024 AssertRC(rc);
1025 return rc;
1026}
1027
1028
1029/**
1030 * Resume notification.
1031 *
1032 * @param pDrvIns The driver instance.
1033 */
1034static DECLCALLBACK(void) drvR3IntNetResume(PPDMDRVINS pDrvIns)
1035{
1036 LogFlow(("drvR3IntNetPowerResume\n"));
1037 PDRVINTNET pThis = PDMINS_2_DATA(pDrvIns, PDRVINTNET);
1038 VMRESUMEREASON enmReason = PDMDrvHlpVMGetResumeReason(pDrvIns);
1039
1040 if (!pThis->fActivateEarlyDeactivateLate)
1041 {
1042 ASMAtomicXchgSize(&pThis->enmRecvState, RECVSTATE_RUNNING);
1043 RTSemEventSignal(pThis->hRecvEvt);
1044 drvR3IntNetUpdateMacAddress(pThis); /* (could be a state restore) */
1045 drvR3IntNetSetActive(pThis, true /* fActive */);
1046 }
1047
1048 switch (enmReason)
1049 {
1050 case VMRESUMEREASON_HOST_RESUME:
1051 {
1052 uint32_t u32TrunkType;
1053 int rc = CFGMR3QueryU32(pDrvIns->pCfg, "TrunkType", &u32TrunkType);
1054 AssertRC(rc);
1055
1056 /*
1057 * Only do the disconnect for bridged networking. Host-only and
1058 * internal networks are not affected by a host resume.
1059 */
1060 if ( RT_SUCCESS(rc)
1061 && u32TrunkType == kIntNetTrunkType_NetFlt)
1062 {
1063 rc = pThis->pIAboveConfigR3->pfnSetLinkState(pThis->pIAboveConfigR3,
1064 PDMNETWORKLINKSTATE_DOWN_RESUME);
1065 AssertRC(rc);
1066 }
1067 break;
1068 }
1069 case VMRESUMEREASON_TELEPORTED:
1070 case VMRESUMEREASON_TELEPORT_FAILED:
1071 {
1072 if ( PDMDrvHlpVMTeleportedAndNotFullyResumedYet(pDrvIns)
1073 && pThis->pIAboveConfigR3)
1074 {
1075 /*
1076 * We've just been teleported and need to drop a hint to the switch
1077 * since we're likely to have changed to a different port. We just
1078 * push out some ethernet frame that doesn't mean anything to anyone.
1079 * For this purpose ethertype 0x801e was chosen since it was registered
1080 * to Sun (dunno what it is/was used for though).
1081 */
1082 union
1083 {
1084 RTNETETHERHDR Hdr;
1085 uint8_t ab[128];
1086 } Frame;
1087 RT_ZERO(Frame);
1088 Frame.Hdr.DstMac.au16[0] = 0xffff;
1089 Frame.Hdr.DstMac.au16[1] = 0xffff;
1090 Frame.Hdr.DstMac.au16[2] = 0xffff;
1091 Frame.Hdr.EtherType = RT_H2BE_U16_C(0x801e);
1092 int rc = pThis->pIAboveConfigR3->pfnGetMac(pThis->pIAboveConfigR3,
1093 &Frame.Hdr.SrcMac);
1094 if (RT_SUCCESS(rc))
1095 rc = drvR3IntNetResumeSend(pThis, &Frame, sizeof(Frame));
1096 if (RT_FAILURE(rc))
1097 LogRel(("IntNet#%u: Sending dummy frame failed: %Rrc\n",
1098 pDrvIns->iInstance, rc));
1099 }
1100 break;
1101 }
1102 default: /* ignore every other resume reason else */
1103 break;
1104 } /* end of switch(enmReason) */
1105}
1106
1107
1108/**
1109 * Suspend notification.
1110 *
1111 * @param pDrvIns The driver instance.
1112 */
1113static DECLCALLBACK(void) drvR3IntNetSuspend(PPDMDRVINS pDrvIns)
1114{
1115 LogFlow(("drvR3IntNetPowerSuspend\n"));
1116 PDRVINTNET pThis = PDMINS_2_DATA(pDrvIns, PDRVINTNET);
1117 if (!pThis->fActivateEarlyDeactivateLate)
1118 {
1119 ASMAtomicXchgSize(&pThis->enmRecvState, RECVSTATE_SUSPENDED);
1120 drvR3IntNetSetActive(pThis, false /* fActive */);
1121 }
1122}
1123
1124
1125/**
1126 * Power On notification.
1127 *
1128 * @param pDrvIns The driver instance.
1129 */
1130static DECLCALLBACK(void) drvR3IntNetPowerOn(PPDMDRVINS pDrvIns)
1131{
1132 LogFlow(("drvR3IntNetPowerOn\n"));
1133 PDRVINTNET pThis = PDMINS_2_DATA(pDrvIns, PDRVINTNET);
1134 if (!pThis->fActivateEarlyDeactivateLate)
1135 {
1136 ASMAtomicXchgSize(&pThis->enmRecvState, RECVSTATE_RUNNING);
1137 RTSemEventSignal(pThis->hRecvEvt);
1138 drvR3IntNetUpdateMacAddress(pThis);
1139 drvR3IntNetSetActive(pThis, true /* fActive */);
1140 }
1141}
1142
1143
1144/**
1145 * @interface_method_impl{PDMDRVREG,pfnRelocate}
1146 */
1147static DECLCALLBACK(void) drvR3IntNetRelocate(PPDMDRVINS pDrvIns, RTGCINTPTR offDelta)
1148{
1149 /* nothing to do here yet */
1150}
1151
1152
1153/**
1154 * Destruct a driver instance.
1155 *
1156 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
1157 * resources can be freed correctly.
1158 *
1159 * @param pDrvIns The driver instance data.
1160 */
1161static DECLCALLBACK(void) drvR3IntNetDestruct(PPDMDRVINS pDrvIns)
1162{
1163 LogFlow(("drvR3IntNetDestruct\n"));
1164 PDRVINTNET pThis = PDMINS_2_DATA(pDrvIns, PDRVINTNET);
1165 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1166
1167 /*
1168 * Indicate to the receive thread that it's time to quit.
1169 */
1170 ASMAtomicXchgSize(&pThis->enmRecvState, RECVSTATE_TERMINATE);
1171 ASMAtomicXchgSize(&pThis->fLinkDown, true);
1172 RTSEMEVENT hRecvEvt = pThis->hRecvEvt;
1173 pThis->hRecvEvt = NIL_RTSEMEVENT;
1174
1175 if (hRecvEvt != NIL_RTSEMEVENT)
1176 RTSemEventSignal(hRecvEvt);
1177
1178 if (pThis->hIf != INTNET_HANDLE_INVALID)
1179 {
1180 INTNETIFABORTWAITREQ AbortWaitReq;
1181 AbortWaitReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
1182 AbortWaitReq.Hdr.cbReq = sizeof(AbortWaitReq);
1183 AbortWaitReq.pSession = NIL_RTR0PTR;
1184 AbortWaitReq.hIf = pThis->hIf;
1185 AbortWaitReq.fNoMoreWaits = true;
1186 int rc = PDMDrvHlpSUPCallVMMR0Ex(pDrvIns, VMMR0_DO_INTNET_IF_ABORT_WAIT, &AbortWaitReq, sizeof(AbortWaitReq));
1187 AssertMsg(RT_SUCCESS(rc) || rc == VERR_SEM_DESTROYED, ("%Rrc\n", rc));
1188 }
1189
1190 /*
1191 * Wait for the threads to terminate.
1192 */
1193 if (pThis->pXmitThread)
1194 {
1195 int rc = PDMR3ThreadDestroy(pThis->pXmitThread, NULL);
1196 AssertRC(rc);
1197 pThis->pXmitThread = NULL;
1198 }
1199
1200 if (pThis->hRecvThread != NIL_RTTHREAD)
1201 {
1202 int rc = RTThreadWait(pThis->hRecvThread, 5000, NULL);
1203 AssertRC(rc);
1204 pThis->hRecvThread = NIL_RTTHREAD;
1205 }
1206
1207 /*
1208 * Deregister statistics in case we're being detached.
1209 */
1210 if (pThis->pBufR3)
1211 {
1212 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->Recv.cStatFrames);
1213 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->Recv.cbStatWritten);
1214 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->Recv.cOverflows);
1215 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->Send.cStatFrames);
1216 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->Send.cbStatWritten);
1217 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->Send.cOverflows);
1218 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->cStatYieldsOk);
1219 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->cStatYieldsNok);
1220 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->cStatLost);
1221 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->cStatBadFrames);
1222 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->StatSend1);
1223 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->StatSend2);
1224 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->StatRecv1);
1225 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->StatRecv2);
1226 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->pBufR3->StatReserved);
1227 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReceivedGso);
1228 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatSentGso);
1229#ifdef VBOX_WITH_STATISTICS
1230 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatReceive);
1231 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatTransmit);
1232#endif
1233 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatXmitWakeupR0);
1234 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatXmitWakeupR3);
1235 PDMDrvHlpSTAMDeregister(pDrvIns, &pThis->StatXmitProcessRing);
1236 }
1237
1238 /*
1239 * Close the interface
1240 */
1241 if (pThis->hIf != INTNET_HANDLE_INVALID)
1242 {
1243 INTNETIFCLOSEREQ CloseReq;
1244 CloseReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
1245 CloseReq.Hdr.cbReq = sizeof(CloseReq);
1246 CloseReq.pSession = NIL_RTR0PTR;
1247 CloseReq.hIf = pThis->hIf;
1248 pThis->hIf = INTNET_HANDLE_INVALID;
1249 int rc = PDMDrvHlpSUPCallVMMR0Ex(pDrvIns, VMMR0_DO_INTNET_IF_CLOSE, &CloseReq, sizeof(CloseReq));
1250 AssertRC(rc);
1251 }
1252
1253
1254 /*
1255 * Destroy the semaphores, S/G cache and xmit lock.
1256 */
1257 if (hRecvEvt != NIL_RTSEMEVENT)
1258 RTSemEventDestroy(hRecvEvt);
1259
1260 if (pThis->hXmitEvt != NIL_SUPSEMEVENT)
1261 {
1262 SUPSemEventClose(pThis->pSupDrvSession, pThis->hXmitEvt);
1263 pThis->hXmitEvt = NIL_SUPSEMEVENT;
1264 }
1265
1266 RTMemCacheDestroy(pThis->hSgCache);
1267 pThis->hSgCache = NIL_RTMEMCACHE;
1268
1269 if (PDMCritSectIsInitialized(&pThis->XmitLock))
1270 PDMR3CritSectDelete(&pThis->XmitLock);
1271}
1272
1273
1274/**
1275 * Queries a policy config value and translates it into open network flag.
1276 *
1277 * @returns VBox status code (error set on failure).
1278 * @param pDrvIns The driver instance.
1279 * @param pszName The value name.
1280 * @param paFlags The open network flag descriptors.
1281 * @param cFlags The number of descriptors.
1282 * @param fFlags The fixed flag.
1283 * @param pfFlags The flags variable to update.
1284 */
1285static int drvIntNetR3CfgGetPolicy(PPDMDRVINS pDrvIns, const char *pszName, PCDRVINTNETFLAG paFlags, size_t cFlags,
1286 uint32_t fFixedFlag, uint32_t *pfFlags)
1287{
1288 char szValue[64];
1289 int rc = CFGMR3QueryString(pDrvIns->pCfg, pszName, szValue, sizeof(szValue));
1290 if (RT_FAILURE(rc))
1291 {
1292 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1293 return VINF_SUCCESS;
1294 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1295 N_("Configuration error: Failed to query value of \"%s\""), pszName);
1296 }
1297
1298 /*
1299 * Check for +fixed first, so it can be stripped off.
1300 */
1301 char *pszSep = strpbrk(szValue, "+,;");
1302 if (pszSep)
1303 {
1304 *pszSep++ = '\0';
1305 const char *pszFixed = RTStrStripL(pszSep);
1306 if (strcmp(pszFixed, "fixed"))
1307 {
1308 *pszSep = '+';
1309 return PDMDrvHlpVMSetError(pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
1310 N_("Configuration error: The value of \"%s\" is unknown: \"%s\""), pszName, szValue);
1311 }
1312 *pfFlags |= fFixedFlag;
1313 RTStrStripR(szValue);
1314 }
1315
1316 /*
1317 * Match against the flag values.
1318 */
1319 size_t i = cFlags;
1320 while (i-- > 0)
1321 if (!strcmp(paFlags[i].pszChoice, szValue))
1322 {
1323 *pfFlags |= paFlags[i].fFlag;
1324 return VINF_SUCCESS;
1325 }
1326
1327 if (!strcmp(szValue, "none"))
1328 return VINF_SUCCESS;
1329
1330 if (!strcmp(szValue, "fixed"))
1331 {
1332 *pfFlags |= fFixedFlag;
1333 return VINF_SUCCESS;
1334 }
1335
1336 return PDMDrvHlpVMSetError(pDrvIns, VERR_INVALID_PARAMETER, RT_SRC_POS,
1337 N_("Configuration error: The value of \"%s\" is unknown: \"%s\""), pszName, szValue);
1338}
1339
1340
1341/**
1342 * Construct a TAP network transport driver instance.
1343 *
1344 * @copydoc FNPDMDRVCONSTRUCT
1345 */
1346static DECLCALLBACK(int) drvR3IntNetConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
1347{
1348 PDRVINTNET pThis = PDMINS_2_DATA(pDrvIns, PDRVINTNET);
1349 bool f;
1350 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1351
1352 /*
1353 * Init the static parts.
1354 */
1355 pThis->pDrvInsR3 = pDrvIns;
1356#ifdef VBOX_WITH_DRVINTNET_IN_R0
1357 pThis->pDrvInsR0 = PDMDRVINS_2_R0PTR(pDrvIns);
1358#endif
1359 pThis->hIf = INTNET_HANDLE_INVALID;
1360 pThis->hRecvThread = NIL_RTTHREAD;
1361 pThis->hRecvEvt = NIL_RTSEMEVENT;
1362 pThis->pXmitThread = NULL;
1363 pThis->hXmitEvt = NIL_SUPSEMEVENT;
1364 pThis->pSupDrvSession = PDMDrvHlpGetSupDrvSession(pDrvIns);
1365 pThis->hSgCache = NIL_RTMEMCACHE;
1366 pThis->enmRecvState = RECVSTATE_SUSPENDED;
1367 pThis->fActivateEarlyDeactivateLate = false;
1368 /* IBase* */
1369 pDrvIns->IBase.pfnQueryInterface = drvR3IntNetIBase_QueryInterface;
1370 pThis->IBaseR0.pfnQueryInterface = drvR3IntNetIBaseR0_QueryInterface;
1371 pThis->IBaseRC.pfnQueryInterface = drvR3IntNetIBaseRC_QueryInterface;
1372 /* INetworkUp */
1373 pThis->INetworkUpR3.pfnBeginXmit = drvIntNetUp_BeginXmit;
1374 pThis->INetworkUpR3.pfnAllocBuf = drvIntNetUp_AllocBuf;
1375 pThis->INetworkUpR3.pfnFreeBuf = drvIntNetUp_FreeBuf;
1376 pThis->INetworkUpR3.pfnSendBuf = drvIntNetUp_SendBuf;
1377 pThis->INetworkUpR3.pfnEndXmit = drvIntNetUp_EndXmit;
1378 pThis->INetworkUpR3.pfnSetPromiscuousMode = drvIntNetUp_SetPromiscuousMode;
1379 pThis->INetworkUpR3.pfnNotifyLinkChanged = drvR3IntNetUp_NotifyLinkChanged;
1380
1381 /*
1382 * Validate the config.
1383 */
1384 PDMDRV_VALIDATE_CONFIG_RETURN(pDrvIns,
1385 "Network"
1386 "|Trunk"
1387 "|TrunkType"
1388 "|ReceiveBufferSize"
1389 "|SendBufferSize"
1390 "|SharedMacOnWire"
1391 "|RestrictAccess"
1392 "|RequireExactPolicyMatch"
1393 "|RequireAsRestrictivePolicy"
1394 "|AccessPolicy"
1395 "|PromiscPolicyClients"
1396 "|PromiscPolicyHost"
1397 "|PromiscPolicyWire"
1398 "|IfPolicyPromisc"
1399 "|TrunkPolicyHost"
1400 "|TrunkPolicyWire"
1401 "|IsService"
1402 "|IgnoreConnectFailure"
1403 "|Workaround1",
1404 "");
1405
1406 /*
1407 * Check that no-one is attached to us.
1408 */
1409 AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
1410 ("Configuration error: Not possible to attach anything to this driver!\n"),
1411 VERR_PDM_DRVINS_NO_ATTACH);
1412
1413 /*
1414 * Query the network port interface.
1415 */
1416 pThis->pIAboveNet = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKDOWN);
1417 if (!pThis->pIAboveNet)
1418 {
1419 AssertMsgFailed(("Configuration error: the above device/driver didn't export the network port interface!\n"));
1420 return VERR_PDM_MISSING_INTERFACE_ABOVE;
1421 }
1422 pThis->pIAboveConfigR3 = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMINETWORKCONFIG);
1423
1424 /*
1425 * Read the configuration.
1426 */
1427 INTNETOPENREQ OpenReq;
1428 RT_ZERO(OpenReq);
1429 OpenReq.Hdr.cbReq = sizeof(OpenReq);
1430 OpenReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
1431 OpenReq.pSession = NIL_RTR0PTR;
1432
1433 /** @cfgm{Network, string}
1434 * The name of the internal network to connect to.
1435 */
1436 int rc = CFGMR3QueryString(pCfg, "Network", OpenReq.szNetwork, sizeof(OpenReq.szNetwork));
1437 if (RT_FAILURE(rc))
1438 return PDMDRV_SET_ERROR(pDrvIns, rc,
1439 N_("Configuration error: Failed to get the \"Network\" value"));
1440 strcpy(pThis->szNetwork, OpenReq.szNetwork);
1441
1442 /** @cfgm{TrunkType, uint32_t, kIntNetTrunkType_None}
1443 * The trunk connection type see INTNETTRUNKTYPE.
1444 */
1445 uint32_t u32TrunkType;
1446 rc = CFGMR3QueryU32(pCfg, "TrunkType", &u32TrunkType);
1447 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1448 u32TrunkType = kIntNetTrunkType_None;
1449 else if (RT_FAILURE(rc))
1450 return PDMDRV_SET_ERROR(pDrvIns, rc,
1451 N_("Configuration error: Failed to get the \"TrunkType\" value"));
1452 OpenReq.enmTrunkType = (INTNETTRUNKTYPE)u32TrunkType;
1453
1454 /** @cfgm{Trunk, string, ""}
1455 * The name of the trunk connection.
1456 */
1457 rc = CFGMR3QueryString(pCfg, "Trunk", OpenReq.szTrunk, sizeof(OpenReq.szTrunk));
1458 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1459 OpenReq.szTrunk[0] = '\0';
1460 else if (RT_FAILURE(rc))
1461 return PDMDRV_SET_ERROR(pDrvIns, rc,
1462 N_("Configuration error: Failed to get the \"Trunk\" value"));
1463
1464 OpenReq.fFlags = 0;
1465
1466 /** @cfgm{SharedMacOnWire, boolean, false}
1467 * Whether to shared the MAC address of the host interface when using the wire. When
1468 * attaching to a wireless NIC this option is usually a requirement.
1469 */
1470 bool fSharedMacOnWire;
1471 rc = CFGMR3QueryBoolDef(pCfg, "SharedMacOnWire", &fSharedMacOnWire, false);
1472 if (RT_FAILURE(rc))
1473 return PDMDRV_SET_ERROR(pDrvIns, rc,
1474 N_("Configuration error: Failed to get the \"SharedMacOnWire\" value"));
1475 if (fSharedMacOnWire)
1476 OpenReq.fFlags |= INTNET_OPEN_FLAGS_SHARED_MAC_ON_WIRE;
1477
1478 /** @cfgm{RestrictAccess, boolean, true}
1479 * Whether to restrict the access to the network or if it should be public.
1480 * Everyone on the computer can connect to a public network.
1481 * @deprecated Use AccessPolicy instead.
1482 */
1483 rc = CFGMR3QueryBool(pCfg, "RestrictAccess", &f);
1484 if (RT_SUCCESS(rc))
1485 {
1486 if (f)
1487 OpenReq.fFlags |= INTNET_OPEN_FLAGS_ACCESS_RESTRICTED;
1488 else
1489 OpenReq.fFlags |= INTNET_OPEN_FLAGS_ACCESS_PUBLIC;
1490 OpenReq.fFlags |= INTNET_OPEN_FLAGS_ACCESS_FIXED;
1491 }
1492 else if (rc != VERR_CFGM_VALUE_NOT_FOUND)
1493 return PDMDRV_SET_ERROR(pDrvIns, rc,
1494 N_("Configuration error: Failed to get the \"RestrictAccess\" value"));
1495
1496 /** @cfgm{RequireExactPolicyMatch, boolean, false}
1497 * Whether to require that the current security and promiscuous policies of
1498 * the network is exactly as the ones specified in this open network
1499 * request. Use this with RequireAsRestrictivePolicy to prevent
1500 * restrictions from being lifted. If no further policy changes are
1501 * desired, apply the relevant fixed flags. */
1502 rc = CFGMR3QueryBoolDef(pCfg, "RequireExactPolicyMatch", &f, false);
1503 if (RT_FAILURE(rc))
1504 return PDMDRV_SET_ERROR(pDrvIns, rc,
1505 N_("Configuration error: Failed to get the \"RequireExactPolicyMatch\" value"));
1506 if (f)
1507 OpenReq.fFlags |= INTNET_OPEN_FLAGS_REQUIRE_EXACT;
1508
1509 /** @cfgm{RequireAsRestrictivePolicy, boolean, false}
1510 * Whether to require that the security and promiscuous policies of the
1511 * network is at least as restrictive as specified this request specifies
1512 * and prevent them being lifted later on.
1513 */
1514 rc = CFGMR3QueryBoolDef(pCfg, "RequireAsRestrictivePolicy", &f, false);
1515 if (RT_FAILURE(rc))
1516 return PDMDRV_SET_ERROR(pDrvIns, rc,
1517 N_("Configuration error: Failed to get the \"RequireAsRestrictivePolicy\" value"));
1518 if (f)
1519 OpenReq.fFlags |= INTNET_OPEN_FLAGS_REQUIRE_AS_RESTRICTIVE_POLICIES;
1520
1521 /** @cfgm{AccessPolicy, string, "none"}
1522 * The access policy of the network:
1523 * public, public+fixed, restricted, restricted+fixed, none or fixed.
1524 *
1525 * A "public" network is accessible to everyone on the same host, while a
1526 * "restricted" one is only accessible to VMs & services started by the
1527 * same user. The "none" policy, which is the default, means no policy
1528 * change or choice is made and that the current (existing network) or
1529 * default (new) policy should be used. */
1530 static const DRVINTNETFLAG s_aAccessPolicyFlags[] =
1531 {
1532 { "public", INTNET_OPEN_FLAGS_ACCESS_PUBLIC },
1533 { "restricted", INTNET_OPEN_FLAGS_ACCESS_RESTRICTED }
1534 };
1535 rc = drvIntNetR3CfgGetPolicy(pDrvIns, "AccessPolicy", &s_aAccessPolicyFlags[0], RT_ELEMENTS(s_aAccessPolicyFlags),
1536 INTNET_OPEN_FLAGS_ACCESS_FIXED, &OpenReq.fFlags);
1537 AssertRCReturn(rc, rc);
1538
1539 /** @cfgm{PromiscPolicyClients, string, "none"}
1540 * The network wide promiscuous mode policy for client (non-trunk)
1541 * interfaces: allow, allow+fixed, deny, deny+fixed, none or fixed. */
1542 static const DRVINTNETFLAG s_aPromiscPolicyClient[] =
1543 {
1544 { "allow", INTNET_OPEN_FLAGS_PROMISC_ALLOW_CLIENTS },
1545 { "deny", INTNET_OPEN_FLAGS_PROMISC_DENY_CLIENTS }
1546 };
1547 rc = drvIntNetR3CfgGetPolicy(pDrvIns, "PromiscPolicyClients", &s_aPromiscPolicyClient[0], RT_ELEMENTS(s_aPromiscPolicyClient),
1548 INTNET_OPEN_FLAGS_PROMISC_FIXED, &OpenReq.fFlags);
1549 AssertRCReturn(rc, rc);
1550 /** @cfgm{PromiscPolicyHost, string, "none"}
1551 * The promiscuous mode policy for the trunk-host
1552 * connection: allow, allow+fixed, deny, deny+fixed, none or fixed. */
1553 static const DRVINTNETFLAG s_aPromiscPolicyHost[] =
1554 {
1555 { "allow", INTNET_OPEN_FLAGS_PROMISC_ALLOW_TRUNK_HOST },
1556 { "deny", INTNET_OPEN_FLAGS_PROMISC_DENY_TRUNK_HOST }
1557 };
1558 rc = drvIntNetR3CfgGetPolicy(pDrvIns, "PromiscPolicyHost", &s_aPromiscPolicyHost[0], RT_ELEMENTS(s_aPromiscPolicyHost),
1559 INTNET_OPEN_FLAGS_PROMISC_FIXED, &OpenReq.fFlags);
1560 AssertRCReturn(rc, rc);
1561 /** @cfgm{PromiscPolicyWire, string, "none"}
1562 * The promiscuous mode policy for the trunk-host
1563 * connection: allow, allow+fixed, deny, deny+fixed, none or fixed. */
1564 static const DRVINTNETFLAG s_aPromiscPolicyWire[] =
1565 {
1566 { "allow", INTNET_OPEN_FLAGS_PROMISC_ALLOW_TRUNK_WIRE },
1567 { "deny", INTNET_OPEN_FLAGS_PROMISC_DENY_TRUNK_WIRE }
1568 };
1569 rc = drvIntNetR3CfgGetPolicy(pDrvIns, "PromiscPolicyWire", &s_aPromiscPolicyWire[0], RT_ELEMENTS(s_aPromiscPolicyWire),
1570 INTNET_OPEN_FLAGS_PROMISC_FIXED, &OpenReq.fFlags);
1571 AssertRCReturn(rc, rc);
1572
1573
1574 /** @cfgm{IfPolicyPromisc, string, "none"}
1575 * The promiscuous mode policy for this
1576 * interface: deny, deny+fixed, allow-all, allow-all+fixed, allow-network,
1577 * allow-network+fixed, none or fixed. */
1578 static const DRVINTNETFLAG s_aIfPolicyPromisc[] =
1579 {
1580 { "allow-all", INTNET_OPEN_FLAGS_IF_PROMISC_ALLOW | INTNET_OPEN_FLAGS_IF_PROMISC_SEE_TRUNK },
1581 { "allow-network", INTNET_OPEN_FLAGS_IF_PROMISC_ALLOW | INTNET_OPEN_FLAGS_IF_PROMISC_NO_TRUNK },
1582 { "deny", INTNET_OPEN_FLAGS_IF_PROMISC_DENY }
1583 };
1584 rc = drvIntNetR3CfgGetPolicy(pDrvIns, "IfPolicyPromisc", &s_aIfPolicyPromisc[0], RT_ELEMENTS(s_aIfPolicyPromisc),
1585 INTNET_OPEN_FLAGS_IF_FIXED, &OpenReq.fFlags);
1586 AssertRCReturn(rc, rc);
1587
1588
1589 /** @cfgm{TrunkPolicyHost, string, "none"}
1590 * The trunk-host policy: promisc, promisc+fixed, enabled, enabled+fixed,
1591 * disabled, disabled+fixed, none or fixed
1592 *
1593 * This can be used to prevent packages to be routed to the host. */
1594 static const DRVINTNETFLAG s_aTrunkPolicyHost[] =
1595 {
1596 { "promisc", INTNET_OPEN_FLAGS_TRUNK_HOST_ENABLED | INTNET_OPEN_FLAGS_TRUNK_HOST_PROMISC_MODE },
1597 { "enabled", INTNET_OPEN_FLAGS_TRUNK_HOST_ENABLED },
1598 { "disabled", INTNET_OPEN_FLAGS_TRUNK_HOST_DISABLED }
1599 };
1600 rc = drvIntNetR3CfgGetPolicy(pDrvIns, "TrunkPolicyHost", &s_aTrunkPolicyHost[0], RT_ELEMENTS(s_aTrunkPolicyHost),
1601 INTNET_OPEN_FLAGS_TRUNK_FIXED, &OpenReq.fFlags);
1602 AssertRCReturn(rc, rc);
1603 /** @cfgm{TrunkPolicyWire, string, "none"}
1604 * The trunk-host policy: promisc, promisc+fixed, enabled, enabled+fixed,
1605 * disabled, disabled+fixed, none or fixed.
1606 *
1607 * This can be used to prevent packages to be routed to the wire. */
1608 static const DRVINTNETFLAG s_aTrunkPolicyWire[] =
1609 {
1610 { "promisc", INTNET_OPEN_FLAGS_TRUNK_WIRE_ENABLED | INTNET_OPEN_FLAGS_TRUNK_WIRE_PROMISC_MODE },
1611 { "enabled", INTNET_OPEN_FLAGS_TRUNK_WIRE_ENABLED },
1612 { "disabled", INTNET_OPEN_FLAGS_TRUNK_WIRE_DISABLED }
1613 };
1614 rc = drvIntNetR3CfgGetPolicy(pDrvIns, "TrunkPolicyWire", &s_aTrunkPolicyWire[0], RT_ELEMENTS(s_aTrunkPolicyWire),
1615 INTNET_OPEN_FLAGS_TRUNK_FIXED, &OpenReq.fFlags);
1616 AssertRCReturn(rc, rc);
1617
1618
1619 /** @cfgm{ReceiveBufferSize, uint32_t, 318 KB}
1620 * The size of the receive buffer.
1621 */
1622 rc = CFGMR3QueryU32(pCfg, "ReceiveBufferSize", &OpenReq.cbRecv);
1623 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1624 OpenReq.cbRecv = 318 * _1K ;
1625 else if (RT_FAILURE(rc))
1626 return PDMDRV_SET_ERROR(pDrvIns, rc,
1627 N_("Configuration error: Failed to get the \"ReceiveBufferSize\" value"));
1628
1629 /** @cfgm{SendBufferSize, uint32_t, 196 KB}
1630 * The size of the send (transmit) buffer.
1631 * This should be more than twice the size of the larges frame size because
1632 * the ring buffer is very simple and doesn't support splitting up frames
1633 * nor inserting padding. So, if this is too close to the frame size the
1634 * header will fragment the buffer such that the frame won't fit on either
1635 * side of it and the code will get very upset about it all.
1636 */
1637 rc = CFGMR3QueryU32(pCfg, "SendBufferSize", &OpenReq.cbSend);
1638 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1639 OpenReq.cbSend = RT_ALIGN_Z(VBOX_MAX_GSO_SIZE * 3, _1K);
1640 else if (RT_FAILURE(rc))
1641 return PDMDRV_SET_ERROR(pDrvIns, rc,
1642 N_("Configuration error: Failed to get the \"SendBufferSize\" value"));
1643 if (OpenReq.cbSend < 128)
1644 return PDMDRV_SET_ERROR(pDrvIns, rc,
1645 N_("Configuration error: The \"SendBufferSize\" value is too small"));
1646 if (OpenReq.cbSend < VBOX_MAX_GSO_SIZE * 3)
1647 LogRel(("DrvIntNet: Warning! SendBufferSize=%u, Recommended minimum size %u butes.\n", OpenReq.cbSend, VBOX_MAX_GSO_SIZE * 4));
1648
1649 /** @cfgm{IsService, boolean, true}
1650 * This alterns the way the thread is suspended and resumed. When it's being used by
1651 * a service such as LWIP/iSCSI it shouldn't suspend immediately like for a NIC.
1652 */
1653 rc = CFGMR3QueryBool(pCfg, "IsService", &pThis->fActivateEarlyDeactivateLate);
1654 if (rc == VERR_CFGM_VALUE_NOT_FOUND)
1655 pThis->fActivateEarlyDeactivateLate = false;
1656 else if (RT_FAILURE(rc))
1657 return PDMDRV_SET_ERROR(pDrvIns, rc,
1658 N_("Configuration error: Failed to get the \"IsService\" value"));
1659
1660
1661 /** @cfgm{IgnoreConnectFailure, boolean, false}
1662 * When set only raise a runtime error if we cannot connect to the internal
1663 * network. */
1664 bool fIgnoreConnectFailure;
1665 rc = CFGMR3QueryBoolDef(pCfg, "IgnoreConnectFailure", &fIgnoreConnectFailure, false);
1666 if (RT_FAILURE(rc))
1667 return PDMDRV_SET_ERROR(pDrvIns, rc,
1668 N_("Configuration error: Failed to get the \"IgnoreConnectFailure\" value"));
1669
1670 /** @cfgm{Workaround1, boolean, depends}
1671 * Enables host specific workarounds, the default is depends on the whether
1672 * we think the host requires it or not.
1673 */
1674 bool fWorkaround1 = false;
1675#ifdef RT_OS_DARWIN
1676 if (OpenReq.fFlags & INTNET_OPEN_FLAGS_SHARED_MAC_ON_WIRE)
1677 {
1678 char szKrnlVer[256];
1679 RTSystemQueryOSInfo(RTSYSOSINFO_RELEASE, szKrnlVer, sizeof(szKrnlVer));
1680 if (strcmp(szKrnlVer, "10.7.0") >= 0)
1681 {
1682 LogRel(("IntNet#%u: Enables the workaround (ip_tos=0) for the little endian ip header checksum problem\n"));
1683 fWorkaround1 = true;
1684 }
1685 }
1686#endif
1687 rc = CFGMR3QueryBoolDef(pCfg, "Workaround1", &fWorkaround1, fWorkaround1);
1688 if (RT_FAILURE(rc))
1689 return PDMDRV_SET_ERROR(pDrvIns, rc,
1690 N_("Configuration error: Failed to get the \"Workaround1\" value"));
1691 if (fWorkaround1)
1692 OpenReq.fFlags |= INTNET_OPEN_FLAGS_WORKAROUND_1;
1693
1694 LogRel(("IntNet#%u: szNetwork={%s} enmTrunkType=%d szTrunk={%s} fFlags=%#x cbRecv=%u cbSend=%u fIgnoreConnectFailure=%RTbool\n",
1695 pDrvIns->iInstance, OpenReq.szNetwork, OpenReq.enmTrunkType, OpenReq.szTrunk, OpenReq.fFlags,
1696 OpenReq.cbRecv, OpenReq.cbSend, fIgnoreConnectFailure));
1697
1698#ifdef RT_OS_DARWIN
1699 /* Temporary hack: attach to a network with the name 'if=en0' and you're hitting the wire. */
1700 if ( !OpenReq.szTrunk[0]
1701 && OpenReq.enmTrunkType == kIntNetTrunkType_None
1702 && !strncmp(pThis->szNetwork, RT_STR_TUPLE("if=en"))
1703 && RT_C_IS_DIGIT(pThis->szNetwork[sizeof("if=en") - 1])
1704 && !pThis->szNetwork[sizeof("if=en")])
1705 {
1706 OpenReq.enmTrunkType = kIntNetTrunkType_NetFlt;
1707 strcpy(OpenReq.szTrunk, &pThis->szNetwork[sizeof("if=") - 1]);
1708 }
1709 /* Temporary hack: attach to a network with the name 'wif=en0' and you're on the air. */
1710 if ( !OpenReq.szTrunk[0]
1711 && OpenReq.enmTrunkType == kIntNetTrunkType_None
1712 && !strncmp(pThis->szNetwork, RT_STR_TUPLE("wif=en"))
1713 && RT_C_IS_DIGIT(pThis->szNetwork[sizeof("wif=en") - 1])
1714 && !pThis->szNetwork[sizeof("wif=en")])
1715 {
1716 OpenReq.enmTrunkType = kIntNetTrunkType_NetFlt;
1717 OpenReq.fFlags |= INTNET_OPEN_FLAGS_SHARED_MAC_ON_WIRE;
1718 strcpy(OpenReq.szTrunk, &pThis->szNetwork[sizeof("wif=") - 1]);
1719 }
1720#endif /* DARWIN */
1721
1722 /*
1723 * Create the event semaphore, S/G cache and xmit critsect.
1724 */
1725 rc = RTSemEventCreate(&pThis->hRecvEvt);
1726 if (RT_FAILURE(rc))
1727 return rc;
1728 rc = RTMemCacheCreate(&pThis->hSgCache, sizeof(PDMSCATTERGATHER), 0, UINT32_MAX, NULL, NULL, pThis, 0);
1729 if (RT_FAILURE(rc))
1730 return rc;
1731 rc = PDMDrvHlpCritSectInit(pDrvIns, &pThis->XmitLock, RT_SRC_POS, "IntNetXmit");
1732 if (RT_FAILURE(rc))
1733 return rc;
1734
1735 /*
1736 * Create the interface.
1737 */
1738 OpenReq.hIf = INTNET_HANDLE_INVALID;
1739 rc = PDMDrvHlpSUPCallVMMR0Ex(pDrvIns, VMMR0_DO_INTNET_OPEN, &OpenReq, sizeof(OpenReq));
1740 if (RT_FAILURE(rc))
1741 {
1742 if (fIgnoreConnectFailure)
1743 {
1744 /*
1745 * During VM restore it is fatal if the network is not available because the
1746 * VM settings are locked and the user has no chance to fix network settings.
1747 * Therefore don't abort but just raise a runtime warning.
1748 */
1749 PDMDrvHlpVMSetRuntimeError(pDrvIns, 0 /*fFlags*/, "HostIfNotConnecting",
1750 N_ ("Cannot connect to the network interface '%s'. The virtual "
1751 "network card will appear to work but the guest will not "
1752 "be able to connect. Please choose a different network in the "
1753 "network settings"), OpenReq.szTrunk);
1754
1755 return VERR_PDM_NO_ATTACHED_DRIVER;
1756 }
1757 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1758 N_("Failed to open/create the internal network '%s'"), pThis->szNetwork);
1759 }
1760
1761 AssertRelease(OpenReq.hIf != INTNET_HANDLE_INVALID);
1762 pThis->hIf = OpenReq.hIf;
1763 Log(("IntNet%d: hIf=%RX32 '%s'\n", pDrvIns->iInstance, pThis->hIf, pThis->szNetwork));
1764
1765 /*
1766 * Get default buffer.
1767 */
1768 INTNETIFGETBUFFERPTRSREQ GetBufferPtrsReq;
1769 GetBufferPtrsReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
1770 GetBufferPtrsReq.Hdr.cbReq = sizeof(GetBufferPtrsReq);
1771 GetBufferPtrsReq.pSession = NIL_RTR0PTR;
1772 GetBufferPtrsReq.hIf = pThis->hIf;
1773 GetBufferPtrsReq.pRing3Buf = NULL;
1774 GetBufferPtrsReq.pRing0Buf = NIL_RTR0PTR;
1775 rc = PDMDrvHlpSUPCallVMMR0Ex(pDrvIns, VMMR0_DO_INTNET_IF_GET_BUFFER_PTRS, &GetBufferPtrsReq, sizeof(GetBufferPtrsReq));
1776 if (RT_FAILURE(rc))
1777 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1778 N_("Failed to get ring-3 buffer for the newly created interface to '%s'"), pThis->szNetwork);
1779 AssertRelease(VALID_PTR(GetBufferPtrsReq.pRing3Buf));
1780 pThis->pBufR3 = GetBufferPtrsReq.pRing3Buf;
1781 pThis->pBufR0 = GetBufferPtrsReq.pRing0Buf;
1782
1783 /*
1784 * Register statistics.
1785 */
1786 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->pBufR3->Recv.cbStatWritten, "Bytes/Received", STAMUNIT_BYTES, "Number of received bytes.");
1787 PDMDrvHlpSTAMRegCounterEx(pDrvIns, &pThis->pBufR3->Send.cbStatWritten, "Bytes/Sent", STAMUNIT_BYTES, "Number of sent bytes.");
1788 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->pBufR3->Recv.cOverflows, "Overflows/Recv", "Number overflows.");
1789 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->pBufR3->Send.cOverflows, "Overflows/Sent", "Number overflows.");
1790 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->pBufR3->Recv.cStatFrames, "Packets/Received", "Number of received packets.");
1791 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->pBufR3->Send.cStatFrames, "Packets/Sent", "Number of sent packets.");
1792 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->StatReceivedGso, "Packets/Received-Gso", "The GSO portion of the received packets.");
1793 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->StatSentGso, "Packets/Sent-Gso", "The GSO portion of the sent packets.");
1794 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->StatSentR0, "Packets/Sent-R0", "The ring-0 portion of the sent packets.");
1795
1796 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->pBufR3->cStatLost, "Packets/Lost", "Number of lost packets.");
1797 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->pBufR3->cStatYieldsNok, "YieldOk", "Number of times yielding helped fix an overflow.");
1798 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->pBufR3->cStatYieldsOk, "YieldNok", "Number of times yielding didn't help fix an overflow.");
1799 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->pBufR3->cStatBadFrames, "BadFrames", "Number of bad frames seed by the consumers.");
1800 PDMDrvHlpSTAMRegProfile(pDrvIns, &pThis->pBufR3->StatSend1, "Send1", "Profiling IntNetR0IfSend.");
1801 PDMDrvHlpSTAMRegProfile(pDrvIns, &pThis->pBufR3->StatSend2, "Send2", "Profiling sending to the trunk.");
1802 PDMDrvHlpSTAMRegProfile(pDrvIns, &pThis->pBufR3->StatRecv1, "Recv1", "Reserved for future receive profiling.");
1803 PDMDrvHlpSTAMRegProfile(pDrvIns, &pThis->pBufR3->StatRecv2, "Recv2", "Reserved for future receive profiling.");
1804 PDMDrvHlpSTAMRegProfile(pDrvIns, &pThis->pBufR3->StatReserved, "Reserved", "Reserved for future use.");
1805#ifdef VBOX_WITH_STATISTICS
1806 PDMDrvHlpSTAMRegProfileAdv(pDrvIns, &pThis->StatReceive, "Receive", "Profiling packet receive runs.");
1807 PDMDrvHlpSTAMRegProfile(pDrvIns, &pThis->StatTransmit, "Transmit", "Profiling packet transmit runs.");
1808#endif
1809 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->StatXmitWakeupR0, "XmitWakeup-R0", "Xmit thread wakeups from ring-0.");
1810 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->StatXmitWakeupR3, "XmitWakeup-R3", "Xmit thread wakeups from ring-3.");
1811 PDMDrvHlpSTAMRegCounter(pDrvIns, &pThis->StatXmitProcessRing, "XmitProcessRing", "Time xmit thread was told to process the ring.");
1812
1813 /*
1814 * Create the async I/O threads.
1815 * Note! Using a PDM thread here doesn't fit with the IsService=true operation.
1816 */
1817 rc = RTThreadCreate(&pThis->hRecvThread, drvR3IntNetRecvThread, pThis, 0,
1818 RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "INTNET-RECV");
1819 if (RT_FAILURE(rc))
1820 {
1821 AssertRC(rc);
1822 return rc;
1823 }
1824
1825 rc = SUPSemEventCreate(pThis->pSupDrvSession, &pThis->hXmitEvt);
1826 AssertRCReturn(rc, rc);
1827
1828 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pXmitThread, pThis,
1829 drvR3IntNetXmitThread, drvR3IntNetXmitWakeUp, 0, RTTHREADTYPE_IO, "INTNET-XMIT");
1830 AssertRCReturn(rc, rc);
1831
1832#ifdef VBOX_WITH_DRVINTNET_IN_R0
1833 /*
1834 * Resolve the ring-0 context interface addresses.
1835 */
1836 rc = pDrvIns->pHlpR3->pfnLdrGetR0InterfaceSymbols(pDrvIns, &pThis->INetworkUpR0, sizeof(pThis->INetworkUpR0),
1837 "drvIntNetUp_", PDMINETWORKUP_SYM_LIST);
1838 AssertLogRelRCReturn(rc, rc);
1839#endif
1840
1841 /*
1842 * Activate data transmission as early as possible
1843 */
1844 if (pThis->fActivateEarlyDeactivateLate)
1845 {
1846 ASMAtomicXchgSize(&pThis->enmRecvState, RECVSTATE_RUNNING);
1847 RTSemEventSignal(pThis->hRecvEvt);
1848
1849 drvR3IntNetUpdateMacAddress(pThis);
1850 drvR3IntNetSetActive(pThis, true /* fActive */);
1851 }
1852
1853 return rc;
1854}
1855
1856
1857
1858/**
1859 * Internal networking transport driver registration record.
1860 */
1861const PDMDRVREG g_DrvIntNet =
1862{
1863 /* u32Version */
1864 PDM_DRVREG_VERSION,
1865 /* szName */
1866 "IntNet",
1867 /* szRCMod */
1868 "VBoxDDRC.rc",
1869 /* szR0Mod */
1870 "VBoxDDR0.r0",
1871 /* pszDescription */
1872 "Internal Networking Transport Driver",
1873 /* fFlags */
1874#ifdef VBOX_WITH_DRVINTNET_IN_R0
1875 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT | PDM_DRVREG_FLAGS_R0,
1876#else
1877 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1878#endif
1879 /* fClass. */
1880 PDM_DRVREG_CLASS_NETWORK,
1881 /* cMaxInstances */
1882 ~0U,
1883 /* cbInstance */
1884 sizeof(DRVINTNET),
1885 /* pfnConstruct */
1886 drvR3IntNetConstruct,
1887 /* pfnDestruct */
1888 drvR3IntNetDestruct,
1889 /* pfnRelocate */
1890 drvR3IntNetRelocate,
1891 /* pfnIOCtl */
1892 NULL,
1893 /* pfnPowerOn */
1894 drvR3IntNetPowerOn,
1895 /* pfnReset */
1896 NULL,
1897 /* pfnSuspend */
1898 drvR3IntNetSuspend,
1899 /* pfnResume */
1900 drvR3IntNetResume,
1901 /* pfnAttach */
1902 NULL,
1903 /* pfnDetach */
1904 NULL,
1905 /* pfnPowerOff */
1906 drvR3IntNetPowerOff,
1907 /* pfnSoftReset */
1908 NULL,
1909 /* u32EndVersion */
1910 PDM_DRVREG_VERSION
1911};
1912
1913#endif /* IN_RING3 */
1914
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use