VirtualBox

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

Last change on this file since 51150 was 48947, checked in by vboxsync, 11 years ago

Devices: Whitespace and svn:keyword cleanups by scm.

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