VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/VBoxNetFlt/VBoxNetFlt.c@ 38640

Last change on this file since 38640 was 33540, checked in by vboxsync, 14 years ago

*: spelling fixes, thanks Timeless!

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 55.2 KB
Line 
1/* $Id: VBoxNetFlt.c 33540 2010-10-28 09:27:05Z vboxsync $ */
2/** @file
3 * VBoxNetFlt - Network Filter Driver (Host), Common Code.
4 */
5
6/*
7 * Copyright (C) 2008-2009 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/** @page pg_netflt VBoxNetFlt - Network Interface Filter
19 *
20 * This is a kernel module that attaches to a real interface on the host and
21 * filters and injects packets.
22 *
23 * In the big picture we're one of the three trunk interface on the internal
24 * network, the one named "NIC Filter Driver": @image html Networking_Overview.gif
25 *
26 *
27 * @section sec_netflt_locking Locking and Potential Races
28 *
29 * The main challenge here is to make sure the netfilter and internal network
30 * instances won't be destroyed while someone is calling into them.
31 *
32 * The main calls into or out of of the filter driver are:
33 * - Send.
34 * - Async send completion (not implemented yet)
35 * - Release by the internal network.
36 * - Receive.
37 * - Disappearance of the host networking interface.
38 * - Reappearance of the host networking interface.
39 *
40 * The latter two calls are can be caused by driver unloading/loading or the
41 * device being physical unplugged (e.g. a USB network device). Actually, the
42 * unload scenario must fervently be prevent as it will cause panics because the
43 * internal network will assume the trunk is around until it releases it.
44 * @todo Need to figure which host allow unloading and block/fix it.
45 *
46 * Currently the netfilter instance lives until the internal network releases
47 * it. So, it is the internal networks responsibility to make sure there are no
48 * active calls when it releases the trunk and destroys the network. The
49 * netfilter assists in this by providing INTNETTRUNKIFPORT::pfnSetState and
50 * INTNETTRUNKIFPORT::pfnWaitForIdle. The trunk state is used to enable/disable
51 * promiscuous mode on the hardware NIC (or similar activation) as well
52 * indicating that disconnect is imminent and no further calls shall be made
53 * into the internal network. After changing the state to disconnecting and
54 * prior to invoking INTNETTRUNKIFPORT::pfnDisconnectAndRelease, the internal
55 * network will use INTNETTRUNKIFPORT::pfnWaitForIdle to wait for any still
56 * active calls to complete.
57 *
58 * The netfilter employs a busy counter and an internal state in addition to the
59 * public trunk state. All these variables are protected using a spinlock.
60 *
61 *
62 * @section sec_netflt_msc Locking / Sequence Diagrams - OBSOLETE
63 *
64 * !OBSOLETE! - THIS WAS THE OLD APPROACH!
65 *
66 * This secion contains a few sequence diagrams describing the problematic
67 * transitions of a host interface filter instance.
68 *
69 * The thing that makes it all a bit problematic is that multiple events may
70 * happen at the same time, and that we have to be very careful to avoid
71 * deadlocks caused by mixing our locks with the ones in the host kernel. The
72 * main events are receive, send, async send completion, disappearance of the
73 * host networking interface and its reappearance. The latter two events are
74 * can be caused by driver unloading/loading or the device being physical
75 * unplugged (e.g. a USB network device).
76 *
77 * The strategy for dealing with these issues are:
78 * - Use a simple state machine.
79 * - Require the user (IntNet) to serialize all its calls to us,
80 * while at the same time not owning any lock used by any of the
81 * the callbacks we might call on receive and async send completion.
82 * - Make sure we're 100% idle before disconnecting, and have a
83 * disconnected status on both sides to fend off async calls.
84 * - Protect the host specific interface handle and the state variables
85 * using a spinlock.
86 *
87 *
88 * @subsection subsec_netflt_msc_dis_rel Disconnect from the network and release - OBSOLETE
89 *
90 * @msc
91 * VM, IntNet, NetFlt, Kernel, Wire;
92 *
93 * VM->IntNet [label="pkt0", linecolor="green", textcolor="green"];
94 * IntNet=>IntNet [label="Lock Network", linecolor="green", textcolor="green" ];
95 * IntNet=>IntNet [label="Route packet -> wire", linecolor="green", textcolor="green" ];
96 * IntNet=>IntNet [label="Unlock Network", linecolor="green", textcolor="green" ];
97 * IntNet=>NetFlt [label="pkt0 to wire", linecolor="green", textcolor="green" ];
98 * NetFlt=>Kernel [label="pkt0 to wire", linecolor="green", textcolor="green"];
99 * Kernel->Wire [label="pkt0 to wire", linecolor="green", textcolor="green"];
100 *
101 * --- [label="Suspending the trunk interface"];
102 * IntNet=>IntNet [label="Lock Network"];
103 *
104 * Wire->Kernel [label="pkt1 - racing us", linecolor="red", textcolor="red"];
105 * Kernel=>>NetFlt [label="pkt1 - racing us", linecolor="red", textcolor="red"];
106 * NetFlt=>>IntNet [label="pkt1 recv - blocks", linecolor="red", textcolor="red"];
107 *
108 * IntNet=>IntNet [label="Mark Trunk Suspended"];
109 * IntNet=>IntNet [label="Unlock Network"];
110 *
111 * IntNet=>NetFlt [label="pfnSetActive(false)"];
112 * NetFlt=>NetFlt [label="Mark inactive (atomic)"];
113 * IntNet<<NetFlt;
114 * IntNet=>NetFlt [label="pfnWaitForIdle(forever)"];
115 *
116 * IntNet=>>NetFlt [label="pkt1 to host", linecolor="red", textcolor="red"];
117 * NetFlt=>>Kernel [label="pkt1 to host", linecolor="red", textcolor="red"];
118 *
119 * Kernel<-Wire [label="pkt0 on wire", linecolor="green", textcolor="green"];
120 * NetFlt<<Kernel [label="pkt0 on wire", linecolor="green", textcolor="green"];
121 * IntNet<<=NetFlt [label="pfnSGRelease", linecolor="green", textcolor="green"];
122 * IntNet<<=IntNet [label="Lock Net, free SG, Unlock Net", linecolor="green", textcolor="green"];
123 * IntNet>>NetFlt [label="pfnSGRelease", linecolor="green", textcolor="green"];
124 * NetFlt<-NetFlt [label="idle", linecolor="green", textcolor="green"];
125 *
126 * IntNet<<NetFlt [label="idle (pfnWaitForIdle)"];
127 *
128 * Wire->Kernel [label="pkt2", linecolor="red", textcolor="red"];
129 * Kernel=>>NetFlt [label="pkt2", linecolor="red", textcolor="red"];
130 * NetFlt=>>Kernel [label="pkt2 to host", linecolor="red", textcolor="red"];
131 *
132 * VM->IntNet [label="pkt3", linecolor="green", textcolor="green"];
133 * IntNet=>IntNet [label="Lock Network", linecolor="green", textcolor="green" ];
134 * IntNet=>IntNet [label="Route packet -> drop", linecolor="green", textcolor="green" ];
135 * IntNet=>IntNet [label="Unlock Network", linecolor="green", textcolor="green" ];
136 *
137 * --- [label="The trunk interface is idle now, disconnect it"];
138 * IntNet=>IntNet [label="Lock Network"];
139 * IntNet=>IntNet [label="Unlink Trunk"];
140 * IntNet=>IntNet [label="Unlock Network"];
141 * IntNet=>NetFlt [label="pfnDisconnectAndRelease"];
142 * NetFlt=>Kernel [label="iflt_detach"];
143 * NetFlt<<=Kernel [label="iff_detached"];
144 * NetFlt>>Kernel [label="iff_detached"];
145 * NetFlt<<Kernel [label="iflt_detach"];
146 * NetFlt=>NetFlt [label="Release"];
147 * IntNet<<NetFlt [label="pfnDisconnectAndRelease"];
148 *
149 * @endmsc
150 *
151 *
152 *
153 * @subsection subsec_netflt_msc_hif_rm Host Interface Removal - OBSOLETE
154 *
155 * The ifnet_t (pIf) is a tricky customer as any reference to it can potentially
156 * race the filter detaching. The simple way of solving it on Darwin is to guard
157 * all access to the pIf member with a spinlock. The other host systems will
158 * probably have similar race conditions, so the spinlock is a generic thing.
159 *
160 * @msc
161 * VM, IntNet, NetFlt, Kernel;
162 *
163 * VM->IntNet [label="pkt0", linecolor="green", textcolor="green"];
164 * IntNet=>IntNet [label="Lock Network", linecolor="green", textcolor="green" ];
165 * IntNet=>IntNet [label="Route packet -> wire", linecolor="green", textcolor="green" ];
166 * IntNet=>IntNet [label="Unlock Network", linecolor="green", textcolor="green" ];
167 * IntNet=>NetFlt [label="pkt0 to wire", linecolor="green", textcolor="green" ];
168 * NetFlt=>Kernel [label="ifnet_reference w/ spinlock", linecolor="green", textcolor="green" ];
169 * NetFlt<<Kernel [label="ifnet_reference", linecolor="green", textcolor="green" ];
170 * NetFlt=>Kernel [label="pkt0 to wire (blocks)", linecolor="green", textcolor="green" ];
171 *
172 * --- [label="The host interface is being disconnected"];
173 * Kernel->NetFlt [label="iff_detached"];
174 * NetFlt=>Kernel [label="ifnet_release w/ spinlock"];
175 * NetFlt<<Kernel [label="ifnet_release"];
176 * NetFlt=>NetFlt [label="fDisconnectedFromHost=true"];
177 * NetFlt>>Kernel [label="iff_detached"];
178 *
179 * NetFlt<<Kernel [label="dropped", linecolor="green", textcolor="green"];
180 * NetFlt=>NetFlt [label="Acquire spinlock", linecolor="green", textcolor="green"];
181 * NetFlt=>Kernel [label="ifnet_release", linecolor="green", textcolor="green"];
182 * NetFlt<<Kernel [label="ifnet_release", linecolor="green", textcolor="green"];
183 * NetFlt=>NetFlt [label="pIf=NULL", linecolor="green", textcolor="green"];
184 * NetFlt=>NetFlt [label="Release spinlock", linecolor="green", textcolor="green"];
185 * IntNet<=NetFlt [label="pfnSGRelease", linecolor="green", textcolor="green"];
186 * IntNet>>NetFlt [label="pfnSGRelease", linecolor="green", textcolor="green"];
187 * IntNet<<NetFlt [label="pkt0 to wire", linecolor="green", textcolor="green"];
188 *
189 * @endmsc
190 *
191 *
192 *
193 * @subsection subsec_netflt_msc_hif_rm Host Interface Rediscovery - OBSOLETE
194 *
195 * The rediscovery is performed when we receive a send request and a certain
196 * period have elapsed since the last attempt, i.e. we're polling it. We
197 * synchronize the rediscovery with disconnection from the internal network
198 * by means of the pfnWaitForIdle call, so no special handling is required.
199 *
200 * @msc
201 * VM2, VM1, IntNet, NetFlt, Kernel, Wire;
202 *
203 * --- [label="Rediscovery conditions are not met"];
204 * VM1->IntNet [label="pkt0"];
205 * IntNet=>IntNet [label="Lock Network"];
206 * IntNet=>IntNet [label="Route packet -> wire"];
207 * IntNet=>IntNet [label="Unlock Network"];
208 * IntNet=>NetFlt [label="pkt0 to wire"];
209 * NetFlt=>NetFlt [label="Read pIf(==NULL) w/ spinlock"];
210 * IntNet<<NetFlt [label="pkt0 to wire (dropped)"];
211 *
212 * --- [label="Rediscovery conditions"];
213 * VM1->IntNet [label="pkt1"];
214 * IntNet=>IntNet [label="Lock Network"];
215 * IntNet=>IntNet [label="Route packet -> wire"];
216 * IntNet=>IntNet [label="Unlock Network"];
217 * IntNet=>NetFlt [label="pkt1 to wire"];
218 * NetFlt=>NetFlt [label="Read pIf(==NULL) w/ spinlock"];
219 * NetFlt=>NetFlt [label="fRediscoveryPending=true w/ spinlock"];
220 * NetFlt=>Kernel [label="ifnet_find_by_name"];
221 * NetFlt<<Kernel [label="ifnet_find_by_name (success)"];
222 *
223 * VM2->IntNet [label="pkt2", linecolor="red", textcolor="red"];
224 * IntNet=>IntNet [label="Lock Network", linecolor="red", textcolor="red"];
225 * IntNet=>IntNet [label="Route packet -> wire", linecolor="red", textcolor="red"];
226 * IntNet=>IntNet [label="Unlock Network", linecolor="red", textcolor="red"];
227 * IntNet=>NetFlt [label="pkt2 to wire", linecolor="red", textcolor="red"];
228 * NetFlt=>NetFlt [label="!pIf || fRediscoveryPending (w/ spinlock)", linecolor="red", textcolor="red"];
229 * IntNet<<NetFlt [label="pkt2 to wire (dropped)", linecolor="red", textcolor="red"];
230
231 * NetFlt=>Kernel [label="iflt_attach"];
232 * NetFlt<<Kernel [label="iflt_attach (success)"];
233 * NetFlt=>NetFlt [label="Acquire spinlock"];
234 * NetFlt=>NetFlt [label="Set pIf and update flags"];
235 * NetFlt=>NetFlt [label="Release spinlock"];
236 *
237 * NetFlt=>Kernel [label="pkt1 to wire"];
238 * Kernel->Wire [label="pkt1 to wire"];
239 * NetFlt<<Kernel [label="pkt1 to wire"];
240 * IntNet<<NetFlt [label="pkt1 to wire"];
241 *
242 *
243 * @endmsc
244 *
245 */
246
247/*******************************************************************************
248* Header Files *
249*******************************************************************************/
250#define LOG_GROUP LOG_GROUP_NET_FLT_DRV
251#include "VBoxNetFltInternal.h"
252
253#include <VBox/sup.h>
254#include <VBox/log.h>
255#include <VBox/err.h>
256#include <iprt/assert.h>
257#include <iprt/string.h>
258#include <iprt/spinlock.h>
259#include <iprt/uuid.h>
260#include <iprt/mem.h>
261#include <iprt/time.h>
262#include <iprt/semaphore.h>
263#include <iprt/thread.h>
264
265
266/*******************************************************************************
267* Defined Constants And Macros *
268*******************************************************************************/
269#define IFPORT_2_VBOXNETFLTINS(pIfPort) \
270 ( (PVBOXNETFLTINS)((uint8_t *)pIfPort - RT_OFFSETOF(VBOXNETFLTINS, MyPort)) )
271
272
273AssertCompileMemberSize(VBOXNETFLTINS, enmState, sizeof(uint32_t));
274
275/**
276 * Sets the enmState member atomically.
277 *
278 * Used for all updates.
279 *
280 * @param pThis The instance.
281 * @param enmNewState The new value.
282 */
283DECLINLINE(void) vboxNetFltSetState(PVBOXNETFLTINS pThis, VBOXNETFTLINSSTATE enmNewState)
284{
285 ASMAtomicWriteU32((uint32_t volatile *)&pThis->enmState, enmNewState);
286}
287
288
289/**
290 * Gets the enmState member atomically.
291 *
292 * Used for all reads.
293 *
294 * @returns The enmState value.
295 * @param pThis The instance.
296 */
297DECLINLINE(VBOXNETFTLINSSTATE) vboxNetFltGetState(PVBOXNETFLTINS pThis)
298{
299 return (VBOXNETFTLINSSTATE)ASMAtomicUoReadU32((uint32_t volatile *)&pThis->enmState);
300}
301
302
303/**
304 * Finds a instance by its name, the caller does the locking.
305 *
306 * @returns Pointer to the instance by the given name. NULL if not found.
307 * @param pGlobals The globals.
308 * @param pszName The name of the instance.
309 */
310static PVBOXNETFLTINS vboxNetFltFindInstanceLocked(PVBOXNETFLTGLOBALS pGlobals, const char *pszName)
311{
312 PVBOXNETFLTINS pCur;
313 for (pCur = pGlobals->pInstanceHead; pCur; pCur = pCur->pNext)
314 if (!strcmp(pszName, pCur->szName))
315 return pCur;
316 return NULL;
317}
318
319
320/**
321 * Finds a instance by its name, will request the mutex.
322 *
323 * No reference to the instance is retained, we're assuming the caller to
324 * already have one but just for some reason doesn't have the pointer to it.
325 *
326 * @returns Pointer to the instance by the given name. NULL if not found.
327 * @param pGlobals The globals.
328 * @param pszName The name of the instance.
329 */
330DECLHIDDEN(PVBOXNETFLTINS) vboxNetFltFindInstance(PVBOXNETFLTGLOBALS pGlobals, const char *pszName)
331{
332 PVBOXNETFLTINS pRet;
333 int rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
334 AssertRCReturn(rc, NULL);
335
336 pRet = vboxNetFltFindInstanceLocked(pGlobals, pszName);
337
338 rc = RTSemFastMutexRelease(pGlobals->hFastMtx);
339 AssertRC(rc);
340 return pRet;
341}
342
343
344/**
345 * Unlinks an instance from the chain.
346 *
347 * @param pGlobals The globals.
348 * @param pToUnlink The instance to unlink.
349 */
350static void vboxNetFltUnlinkLocked(PVBOXNETFLTGLOBALS pGlobals, PVBOXNETFLTINS pToUnlink)
351{
352 if (pGlobals->pInstanceHead == pToUnlink)
353 pGlobals->pInstanceHead = pToUnlink->pNext;
354 else
355 {
356 PVBOXNETFLTINS pCur;
357 for (pCur = pGlobals->pInstanceHead; pCur; pCur = pCur->pNext)
358 if (pCur->pNext == pToUnlink)
359 {
360 pCur->pNext = pToUnlink->pNext;
361 break;
362 }
363 Assert(pCur);
364 }
365 pToUnlink->pNext = NULL;
366}
367
368
369/**
370 * Performs interface rediscovery if it was disconnected from the host.
371 *
372 * @returns true if successfully rediscovered and connected, false if not.
373 * @param pThis The instance.
374 */
375static bool vboxNetFltMaybeRediscovered(PVBOXNETFLTINS pThis)
376{
377 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
378 uint64_t Now;
379 bool fRediscovered;
380 bool fDoIt;
381
382 /*
383 * Don't do rediscovery if we're called with preemption disabled.
384 *
385 * Note! This may cause trouble if we're always called with preemption
386 * disabled and vboxNetFltOsMaybeRediscovered actually does some real
387 * work. For the time being though, only Darwin and FreeBSD depends
388 * on these call outs and neither supports sending with preemption
389 * disabled.
390 */
391 if (!RTThreadPreemptIsEnabled(NIL_RTTHREAD))
392 return false;
393
394 /*
395 * Rediscovered already? Time to try again?
396 */
397 Now = RTTimeNanoTS();
398 RTSpinlockAcquireNoInts(pThis->hSpinlock, &Tmp);
399
400 fRediscovered = !ASMAtomicUoReadBool(&pThis->fDisconnectedFromHost);
401 fDoIt = !fRediscovered
402 && !ASMAtomicUoReadBool(&pThis->fRediscoveryPending)
403 && Now - ASMAtomicUoReadU64(&pThis->NanoTSLastRediscovery) > UINT64_C(5000000000); /* 5 sec */
404 if (fDoIt)
405 ASMAtomicWriteBool(&pThis->fRediscoveryPending, true);
406
407 RTSpinlockReleaseNoInts(pThis->hSpinlock, &Tmp);
408
409 /*
410 * Call the OS specific code to do the job.
411 * Update the state when the call returns, that is everything except for
412 * the fDisconnectedFromHost flag which the OS specific code shall set.
413 */
414 if (fDoIt)
415 {
416 fRediscovered = vboxNetFltOsMaybeRediscovered(pThis);
417
418 Assert(!fRediscovered || !ASMAtomicUoReadBool(&pThis->fDisconnectedFromHost));
419
420 ASMAtomicUoWriteU64(&pThis->NanoTSLastRediscovery, RTTimeNanoTS());
421 ASMAtomicWriteBool(&pThis->fRediscoveryPending, false);
422
423 if (fRediscovered)
424 /** @todo this isn't 100% serialized. */
425 vboxNetFltPortOsSetActive(pThis, pThis->enmTrunkState == INTNETTRUNKIFSTATE_ACTIVE);
426 }
427
428 return fRediscovered;
429}
430
431
432/**
433 * @copydoc INTNETTRUNKIFPORT::pfnXmit
434 */
435static DECLCALLBACK(int) vboxNetFltPortXmit(PINTNETTRUNKIFPORT pIfPort, void *pvIfData, PINTNETSG pSG, uint32_t fDst)
436{
437 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
438 int rc = VINF_SUCCESS;
439
440 /*
441 * Input validation.
442 */
443 AssertPtr(pThis);
444 AssertPtr(pSG);
445 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
446 AssertReturn(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Connected, VERR_INVALID_STATE);
447
448 /*
449 * Do a busy retain and then make sure we're connected to the interface
450 * before invoking the OS specific code.
451 */
452 if (RT_LIKELY(vboxNetFltTryRetainBusyActive(pThis)))
453 {
454 if ( !ASMAtomicUoReadBool(&pThis->fDisconnectedFromHost)
455 || vboxNetFltMaybeRediscovered(pThis))
456 rc = vboxNetFltPortOsXmit(pThis, pvIfData, pSG, fDst);
457 vboxNetFltRelease(pThis, true /* fBusy */);
458 }
459
460 return rc;
461}
462
463
464/**
465 * @copydoc INTNETTRUNKIFPORT::pfnWaitForIdle
466 */
467static DECLCALLBACK(int) vboxNetFltPortWaitForIdle(PINTNETTRUNKIFPORT pIfPort, uint32_t cMillies)
468{
469 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
470 int rc;
471
472 /*
473 * Input validation.
474 */
475 AssertPtr(pThis);
476 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
477 AssertReturn(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Connected, VERR_INVALID_STATE);
478 AssertReturn(pThis->enmTrunkState == INTNETTRUNKIFSTATE_DISCONNECTING, VERR_INVALID_STATE);
479
480 /*
481 * Go to sleep on the semaphore after checking the busy count.
482 */
483 vboxNetFltRetain(pThis, false /* fBusy */);
484
485 rc = VINF_SUCCESS;
486 while (pThis->cBusy && RT_SUCCESS(rc))
487 rc = RTSemEventWait(pThis->hEventIdle, cMillies); /** @todo make interruptible? */
488
489 vboxNetFltRelease(pThis, false /* fBusy */);
490
491 return rc;
492}
493
494
495/**
496 * @copydoc INTNETTRUNKIFPORT::pfnSetState
497 */
498static DECLCALLBACK(INTNETTRUNKIFSTATE) vboxNetFltPortSetState(PINTNETTRUNKIFPORT pIfPort, INTNETTRUNKIFSTATE enmState)
499{
500 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
501 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
502 INTNETTRUNKIFSTATE enmOldTrunkState;
503
504 /*
505 * Input validation.
506 */
507 AssertPtr(pThis);
508 AssertPtr(pThis->pGlobals);
509 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
510 AssertReturn(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Connected, INTNETTRUNKIFSTATE_INVALID);
511 AssertReturn(enmState > INTNETTRUNKIFSTATE_INVALID && enmState < INTNETTRUNKIFSTATE_END,
512 INTNETTRUNKIFSTATE_INVALID);
513
514 /*
515 * Take the lock and change the state.
516 */
517 RTSpinlockAcquireNoInts(pThis->hSpinlock, &Tmp);
518 enmOldTrunkState = pThis->enmTrunkState;
519 if (enmOldTrunkState != enmState)
520 ASMAtomicWriteU32((uint32_t volatile *)&pThis->enmTrunkState, enmState);
521 RTSpinlockReleaseNoInts(pThis->hSpinlock, &Tmp);
522
523 /*
524 * If the state change indicates that the trunk has become active or
525 * inactive, call the OS specific part so they can work the promiscuous
526 * settings and such.
527 * Note! The caller makes sure there are no concurrent pfnSetState calls.
528 */
529 if ((enmOldTrunkState == INTNETTRUNKIFSTATE_ACTIVE) != (enmState == INTNETTRUNKIFSTATE_ACTIVE))
530 vboxNetFltPortOsSetActive(pThis, (enmState == INTNETTRUNKIFSTATE_ACTIVE));
531
532 return enmOldTrunkState;
533}
534
535
536/**
537 * @copydoc INTNETTRUNKIFPORT::pfnNotifyMacAddress
538 */
539static DECLCALLBACK(void) vboxNetFltPortNotifyMacAddress(PINTNETTRUNKIFPORT pIfPort, void *pvIfData, PCRTMAC pMac)
540{
541 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
542
543 /*
544 * Input validation.
545 */
546 AssertPtr(pThis);
547 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
548
549 vboxNetFltRetain(pThis, false /* fBusy */);
550 vboxNetFltPortOsNotifyMacAddress(pThis, pvIfData, pMac);
551 vboxNetFltRelease(pThis, false /* fBusy */);
552}
553
554
555/**
556 * @copydoc INTNETTRUNKIFPORT::pfnConnectInterface
557 */
558static DECLCALLBACK(int) vboxNetFltPortConnectInterface(PINTNETTRUNKIFPORT pIfPort, void *pvIf, void **ppvIfData)
559{
560 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
561 int rc;
562
563 /*
564 * Input validation.
565 */
566 AssertPtr(pThis);
567 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
568
569 vboxNetFltRetain(pThis, false /* fBusy */);
570 rc = vboxNetFltPortOsConnectInterface(pThis, pvIf, ppvIfData);
571 vboxNetFltRelease(pThis, false /* fBusy */);
572
573 return rc;
574}
575
576
577/**
578 * @copydoc INTNETTRUNKIFPORT::pfnDisconnectInterface
579 */
580static DECLCALLBACK(void) vboxNetFltPortDisconnectInterface(PINTNETTRUNKIFPORT pIfPort, void *pvIfData)
581{
582 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
583 int rc;
584
585 /*
586 * Input validation.
587 */
588 AssertPtr(pThis);
589 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
590
591 vboxNetFltRetain(pThis, false /* fBusy */);
592 rc = vboxNetFltPortOsDisconnectInterface(pThis, pvIfData);
593 vboxNetFltRelease(pThis, false /* fBusy */);
594 AssertRC(rc); /** @todo fix vboxNetFltPortOsDisconnectInterface. */
595}
596
597
598/**
599 * @copydoc INTNETTRUNKIFPORT::pfnDisconnectAndRelease
600 */
601static DECLCALLBACK(void) vboxNetFltPortDisconnectAndRelease(PINTNETTRUNKIFPORT pIfPort)
602{
603 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
604 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
605
606 /*
607 * Serious paranoia.
608 */
609 AssertPtr(pThis);
610 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
611 Assert(pThis->MyPort.u32VersionEnd == INTNETTRUNKIFPORT_VERSION);
612 AssertPtr(pThis->pGlobals);
613 Assert(pThis->hEventIdle != NIL_RTSEMEVENT);
614 Assert(pThis->hSpinlock != NIL_RTSPINLOCK);
615 Assert(pThis->szName[0]);
616
617 Assert(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Connected);
618 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_DISCONNECTING);
619 Assert(!pThis->fRediscoveryPending);
620 Assert(!pThis->cBusy);
621
622 /*
623 * Disconnect and release it.
624 */
625 RTSpinlockAcquireNoInts(pThis->hSpinlock, &Tmp);
626 vboxNetFltSetState(pThis, kVBoxNetFltInsState_Disconnecting);
627 RTSpinlockReleaseNoInts(pThis->hSpinlock, &Tmp);
628
629 vboxNetFltOsDisconnectIt(pThis);
630 pThis->pSwitchPort = NULL;
631
632#ifdef VBOXNETFLT_STATIC_CONFIG
633 RTSpinlockAcquireNoInts(pThis->hSpinlock, &Tmp);
634 vboxNetFltSetState(pThis, kVBoxNetFltInsState_Unconnected);
635 RTSpinlockReleaseNoInts(pThis->hSpinlock, &Tmp);
636#endif
637
638 vboxNetFltRelease(pThis, false /* fBusy */);
639}
640
641
642/**
643 * Destroy a device that has been disconnected from the switch.
644 *
645 * @returns true if the instance is destroyed, false otherwise.
646 * @param pThis The instance to be destroyed. This is
647 * no longer valid when this function returns.
648 */
649static bool vboxNetFltDestroyInstance(PVBOXNETFLTINS pThis)
650{
651 PVBOXNETFLTGLOBALS pGlobals = pThis->pGlobals;
652 uint32_t cRefs = ASMAtomicUoReadU32((uint32_t volatile *)&pThis->cRefs);
653 int rc;
654 LogFlow(("vboxNetFltDestroyInstance: pThis=%p (%s)\n", pThis, pThis->szName));
655
656 /*
657 * Validate the state.
658 */
659#ifdef VBOXNETFLT_STATIC_CONFIG
660 Assert( vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Disconnecting
661 || vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Unconnected);
662#else
663 Assert(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Disconnecting);
664#endif
665 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_DISCONNECTING);
666 Assert(!pThis->fRediscoveryPending);
667 Assert(!pThis->cRefs);
668 Assert(!pThis->cBusy);
669 Assert(!pThis->pSwitchPort);
670
671 /*
672 * Make sure the state is 'disconnecting' / 'destroying' and let the OS
673 * specific code do its part of the cleanup outside the mutex.
674 */
675 rc = RTSemFastMutexRequest(pGlobals->hFastMtx); AssertRC(rc);
676 vboxNetFltSetState(pThis, kVBoxNetFltInsState_Disconnecting);
677 RTSemFastMutexRelease(pGlobals->hFastMtx);
678
679 vboxNetFltOsDeleteInstance(pThis);
680
681 /*
682 * Unlink the instance and free up its resources.
683 */
684 rc = RTSemFastMutexRequest(pGlobals->hFastMtx); AssertRC(rc);
685 vboxNetFltSetState(pThis, kVBoxNetFltInsState_Destroyed);
686 vboxNetFltUnlinkLocked(pGlobals, pThis);
687 RTSemFastMutexRelease(pGlobals->hFastMtx);
688
689 RTSemEventDestroy(pThis->hEventIdle);
690 pThis->hEventIdle = NIL_RTSEMEVENT;
691 RTSpinlockDestroy(pThis->hSpinlock);
692 pThis->hSpinlock = NIL_RTSPINLOCK;
693 RTMemFree(pThis);
694
695 NOREF(cRefs);
696
697 return true;
698}
699
700
701/**
702 * Releases a reference to the specified instance.
703 *
704 * This method will destroy the instance when the count reaches 0.
705 * It will also take care of decrementing the counter and idle wakeup.
706 *
707 * @param pThis The instance.
708 * @param fBusy Whether the busy counter should be decremented too.
709 */
710DECLHIDDEN(void) vboxNetFltRelease(PVBOXNETFLTINS pThis, bool fBusy)
711{
712 uint32_t cRefs;
713
714 /*
715 * Paranoid Android.
716 */
717 AssertPtr(pThis);
718 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
719 Assert(pThis->MyPort.u32VersionEnd == INTNETTRUNKIFPORT_VERSION);
720 Assert( vboxNetFltGetState(pThis) > kVBoxNetFltInsState_Invalid
721 && vboxNetFltGetState(pThis) < kVBoxNetFltInsState_Destroyed);
722 AssertPtr(pThis->pGlobals);
723 Assert(pThis->hEventIdle != NIL_RTSEMEVENT);
724 Assert(pThis->hSpinlock != NIL_RTSPINLOCK);
725 Assert(pThis->szName[0]);
726
727 /*
728 * Work the busy counter.
729 */
730 if (fBusy)
731 {
732 cRefs = ASMAtomicDecU32(&pThis->cBusy);
733 if (!cRefs)
734 {
735 int rc = RTSemEventSignal(pThis->hEventIdle);
736 AssertRC(rc);
737 }
738 else
739 Assert(cRefs < UINT32_MAX / 2);
740 }
741
742 /*
743 * The object reference counting.
744 */
745 cRefs = ASMAtomicDecU32(&pThis->cRefs);
746 if (!cRefs)
747 vboxNetFltDestroyInstance(pThis);
748 else
749 Assert(cRefs < UINT32_MAX / 2);
750}
751
752
753/**
754 * @copydoc INTNETTRUNKIFPORT::pfnRetain
755 */
756static DECLCALLBACK(void) vboxNetFltPortRelease(PINTNETTRUNKIFPORT pIfPort)
757{
758 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
759 vboxNetFltRelease(pThis, false /* fBusy */);
760}
761
762
763/**
764 * Retains a reference to the specified instance and a busy reference too.
765 *
766 * @param pThis The instance.
767 * @param fBusy Whether the busy counter should be incremented as well.
768 */
769DECLHIDDEN(void) vboxNetFltRetain(PVBOXNETFLTINS pThis, bool fBusy)
770{
771 uint32_t cRefs;
772
773 /*
774 * Paranoid Android.
775 */
776 AssertPtr(pThis);
777 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
778 Assert(pThis->MyPort.u32VersionEnd == INTNETTRUNKIFPORT_VERSION);
779 Assert( vboxNetFltGetState(pThis) > kVBoxNetFltInsState_Invalid
780 && vboxNetFltGetState(pThis) < kVBoxNetFltInsState_Destroyed);
781 AssertPtr(pThis->pGlobals);
782 Assert(pThis->hEventIdle != NIL_RTSEMEVENT);
783 Assert(pThis->hSpinlock != NIL_RTSPINLOCK);
784 Assert(pThis->szName[0]);
785
786 /*
787 * Retain the object.
788 */
789 cRefs = ASMAtomicIncU32(&pThis->cRefs);
790 Assert(cRefs > 1 && cRefs < UINT32_MAX / 2);
791
792 /*
793 * Work the busy counter.
794 */
795 if (fBusy)
796 {
797 cRefs = ASMAtomicIncU32(&pThis->cBusy);
798 Assert(cRefs > 0 && cRefs < UINT32_MAX / 2);
799 }
800
801 NOREF(cRefs);
802}
803
804
805/**
806 * Tries to retain the device as busy if the trunk is active.
807 *
808 * This is used before calling pfnRecv or pfnPreRecv.
809 *
810 * @returns true if we succeeded in retaining a busy reference to the active
811 * device. false if we failed.
812 * @param pThis The instance.
813 */
814DECLHIDDEN(bool) vboxNetFltTryRetainBusyActive(PVBOXNETFLTINS pThis)
815{
816 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
817 uint32_t cRefs;
818 bool fRc;
819
820 /*
821 * Paranoid Android.
822 */
823 AssertPtr(pThis);
824 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
825 Assert(pThis->MyPort.u32VersionEnd == INTNETTRUNKIFPORT_VERSION);
826 Assert( vboxNetFltGetState(pThis) > kVBoxNetFltInsState_Invalid
827 && vboxNetFltGetState(pThis) < kVBoxNetFltInsState_Destroyed);
828 AssertPtr(pThis->pGlobals);
829 Assert(pThis->hEventIdle != NIL_RTSEMEVENT);
830 Assert(pThis->hSpinlock != NIL_RTSPINLOCK);
831 Assert(pThis->szName[0]);
832
833 /*
834 * Do the retaining and checking behind the spinlock.
835 */
836 RTSpinlockAcquireNoInts(pThis->hSpinlock, &Tmp);
837 fRc = pThis->enmTrunkState == INTNETTRUNKIFSTATE_ACTIVE;
838 if (fRc)
839 {
840 cRefs = ASMAtomicIncU32(&pThis->cRefs);
841 AssertMsg(cRefs > 1 && cRefs < UINT32_MAX / 2, ("%d\n", cRefs)); NOREF(cRefs);
842
843 cRefs = ASMAtomicIncU32(&pThis->cBusy);
844 AssertMsg(cRefs >= 1 && cRefs < UINT32_MAX / 2, ("%d\n", cRefs)); NOREF(cRefs);
845 }
846 RTSpinlockReleaseNoInts(pThis->hSpinlock, &Tmp);
847
848 return fRc;
849}
850
851
852/**
853 * Tries to retain the device as busy if the trunk is not disconnecting.
854 *
855 * This is used before reporting stuff to the internal network.
856 *
857 * @returns true if we succeeded in retaining a busy reference to the active
858 * device. false if we failed.
859 * @param pThis The instance.
860 */
861DECLHIDDEN(bool) vboxNetFltTryRetainBusyNotDisconnected(PVBOXNETFLTINS pThis)
862{
863 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
864 uint32_t cRefs;
865 bool fRc;
866
867 /*
868 * Paranoid Android.
869 */
870 AssertPtr(pThis);
871 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
872 Assert(pThis->MyPort.u32VersionEnd == INTNETTRUNKIFPORT_VERSION);
873 Assert( vboxNetFltGetState(pThis) > kVBoxNetFltInsState_Invalid
874 && vboxNetFltGetState(pThis) < kVBoxNetFltInsState_Destroyed);
875 AssertPtr(pThis->pGlobals);
876 Assert(pThis->hEventIdle != NIL_RTSEMEVENT);
877 Assert(pThis->hSpinlock != NIL_RTSPINLOCK);
878 Assert(pThis->szName[0]);
879
880 /*
881 * Do the retaining and checking behind the spinlock.
882 */
883 RTSpinlockAcquireNoInts(pThis->hSpinlock, &Tmp);
884 fRc = pThis->enmTrunkState == INTNETTRUNKIFSTATE_ACTIVE
885 || pThis->enmTrunkState == INTNETTRUNKIFSTATE_INACTIVE;
886 if (fRc)
887 {
888 cRefs = ASMAtomicIncU32(&pThis->cRefs);
889 AssertMsg(cRefs > 1 && cRefs < UINT32_MAX / 2, ("%d\n", cRefs)); NOREF(cRefs);
890
891 cRefs = ASMAtomicIncU32(&pThis->cBusy);
892 AssertMsg(cRefs >= 1 && cRefs < UINT32_MAX / 2, ("%d\n", cRefs)); NOREF(cRefs);
893 }
894 RTSpinlockReleaseNoInts(pThis->hSpinlock, &Tmp);
895
896 return fRc;
897}
898
899
900/**
901 * @copydoc INTNETTRUNKIFPORT::pfnRetain
902 */
903static DECLCALLBACK(void) vboxNetFltPortRetain(PINTNETTRUNKIFPORT pIfPort)
904{
905 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
906 vboxNetFltRetain(pThis, false /* fBusy */);
907}
908
909
910/**
911 * Connects the instance to the specified switch port.
912 *
913 * Called while owning the lock. We're ASSUMING that the internal
914 * networking code is already owning an recursive mutex, so, there
915 * will be no deadlocks when vboxNetFltOsConnectIt calls back into
916 * it for setting preferences.
917 *
918 * @returns VBox status code.
919 * @param pThis The instance.
920 * @param pSwitchPort The port on the internal network 'switch'.
921 * @param ppIfPort Where to return our port interface.
922 */
923static int vboxNetFltConnectIt(PVBOXNETFLTINS pThis, PINTNETTRUNKSWPORT pSwitchPort, PINTNETTRUNKIFPORT *ppIfPort)
924{
925 int rc;
926
927 /*
928 * Validate state.
929 */
930 Assert(!pThis->fRediscoveryPending);
931 Assert(!pThis->cBusy);
932#ifdef VBOXNETFLT_STATIC_CONFIG
933 Assert(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Unconnected);
934#else
935 Assert(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Initializing);
936#endif
937 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_INACTIVE);
938
939 /*
940 * Do the job.
941 * Note that we're calling the os stuff while owning the semaphore here.
942 */
943 pThis->pSwitchPort = pSwitchPort;
944 rc = vboxNetFltOsConnectIt(pThis);
945 if (RT_SUCCESS(rc))
946 {
947 vboxNetFltSetState(pThis, kVBoxNetFltInsState_Connected);
948 *ppIfPort = &pThis->MyPort;
949 }
950 else
951 pThis->pSwitchPort = NULL;
952
953 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_INACTIVE);
954 return rc;
955}
956
957
958/**
959 * Creates a new instance.
960 *
961 * The new instance will be in the suspended state in a dynamic config and in
962 * the inactive in a static one.
963 *
964 * Called without owning the lock, but will request is several times.
965 *
966 * @returns VBox status code.
967 * @param pGlobals The globals.
968 * @param pszName The instance name.
969 * @param pSwitchPort The port on the switch that we're connected with (dynamic only).
970 * @param fNoPromisc Do not attempt going into promiscuous mode.
971 * @param pvContext Context argument for vboxNetFltOsInitInstance.
972 * @param ppIfPort Where to store the pointer to our port interface (dynamic only).
973 */
974static int vboxNetFltNewInstance(PVBOXNETFLTGLOBALS pGlobals, const char *pszName, PINTNETTRUNKSWPORT pSwitchPort,
975 bool fNoPromisc, void *pvContext, PINTNETTRUNKIFPORT *ppIfPort)
976{
977 /*
978 * Allocate and initialize a new instance before requesting the mutex.
979 * Note! That in a static config we'll initialize the trunk state to
980 * disconnecting and flip it in vboxNetFltFactoryCreateAndConnect
981 * later on. This better reflext the state and it works better with
982 * assertions in the destruction path.
983 */
984 int rc;
985 size_t const cchName = strlen(pszName);
986 PVBOXNETFLTINS pNew = (PVBOXNETFLTINS)RTMemAllocZ(RT_OFFSETOF(VBOXNETFLTINS, szName[cchName + 1]));
987 if (!pNew)
988 return VERR_INTNET_FLT_IF_FAILED;
989 pNew->pNext = NULL;
990 pNew->MyPort.u32Version = INTNETTRUNKIFPORT_VERSION;
991 pNew->MyPort.pfnRetain = vboxNetFltPortRetain;
992 pNew->MyPort.pfnRelease = vboxNetFltPortRelease;
993 pNew->MyPort.pfnDisconnectAndRelease= vboxNetFltPortDisconnectAndRelease;
994 pNew->MyPort.pfnSetState = vboxNetFltPortSetState;
995 pNew->MyPort.pfnWaitForIdle = vboxNetFltPortWaitForIdle;
996 pNew->MyPort.pfnXmit = vboxNetFltPortXmit;
997 pNew->MyPort.pfnNotifyMacAddress = vboxNetFltPortNotifyMacAddress;
998 pNew->MyPort.pfnConnectInterface = vboxNetFltPortConnectInterface;
999 pNew->MyPort.pfnDisconnectInterface = vboxNetFltPortDisconnectInterface;
1000 pNew->MyPort.u32VersionEnd = INTNETTRUNKIFPORT_VERSION;
1001 pNew->pSwitchPort = pSwitchPort;
1002 pNew->pGlobals = pGlobals;
1003 pNew->hSpinlock = NIL_RTSPINLOCK;
1004 pNew->enmState = kVBoxNetFltInsState_Initializing;
1005#ifdef VBOXNETFLT_STATIC_CONFIG
1006 pNew->enmTrunkState = INTNETTRUNKIFSTATE_DISCONNECTING;
1007#else
1008 pNew->enmTrunkState = INTNETTRUNKIFSTATE_INACTIVE;
1009#endif
1010 pNew->fDisconnectedFromHost = false;
1011 pNew->fRediscoveryPending = false;
1012 pNew->fDisablePromiscuous = fNoPromisc;
1013 pNew->NanoTSLastRediscovery = INT64_MAX;
1014 pNew->cRefs = 1;
1015 pNew->cBusy = 0;
1016 pNew->hEventIdle = NIL_RTSEMEVENT;
1017 memcpy(pNew->szName, pszName, cchName + 1);
1018
1019 rc = RTSpinlockCreate(&pNew->hSpinlock);
1020 if (RT_SUCCESS(rc))
1021 {
1022 rc = RTSemEventCreate(&pNew->hEventIdle);
1023 if (RT_SUCCESS(rc))
1024 {
1025 rc = vboxNetFltOsPreInitInstance(pNew);
1026 if (RT_SUCCESS(rc))
1027 {
1028 /*
1029 * Insert the instance into the chain, checking for
1030 * duplicates first of course (race).
1031 */
1032 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1033 if (RT_SUCCESS(rc))
1034 {
1035 if (!vboxNetFltFindInstanceLocked(pGlobals, pszName))
1036 {
1037 pNew->pNext = pGlobals->pInstanceHead;
1038 pGlobals->pInstanceHead = pNew;
1039 RTSemFastMutexRelease(pGlobals->hFastMtx);
1040
1041 /*
1042 * Call the OS specific initialization code.
1043 */
1044 rc = vboxNetFltOsInitInstance(pNew, pvContext);
1045 RTSemFastMutexRequest(pGlobals->hFastMtx);
1046 if (RT_SUCCESS(rc))
1047 {
1048#ifdef VBOXNETFLT_STATIC_CONFIG
1049 /*
1050 * Static instances are unconnected at birth.
1051 */
1052 Assert(!pSwitchPort);
1053 pNew->enmState = kVBoxNetFltInsState_Unconnected;
1054 RTSemFastMutexRelease(pGlobals->hFastMtx);
1055 *ppIfPort = &pNew->MyPort;
1056 return rc;
1057
1058#else /* !VBOXNETFLT_STATIC_CONFIG */
1059 /*
1060 * Connect it as well, the OS specific bits has to be done outside
1061 * the lock as they may call back to into intnet.
1062 */
1063 rc = vboxNetFltConnectIt(pNew, pSwitchPort, ppIfPort);
1064 if (RT_SUCCESS(rc))
1065 {
1066 RTSemFastMutexRelease(pGlobals->hFastMtx);
1067 Assert(*ppIfPort == &pNew->MyPort);
1068 return rc;
1069 }
1070
1071 /* Bail out (failed). */
1072 vboxNetFltOsDeleteInstance(pNew);
1073#endif /* !VBOXNETFLT_STATIC_CONFIG */
1074 }
1075 vboxNetFltUnlinkLocked(pGlobals, pNew);
1076 }
1077 else
1078 rc = VERR_INTNET_FLT_IF_BUSY;
1079 RTSemFastMutexRelease(pGlobals->hFastMtx);
1080 }
1081 }
1082 RTSemEventDestroy(pNew->hEventIdle);
1083 }
1084 RTSpinlockDestroy(pNew->hSpinlock);
1085 }
1086
1087 RTMemFree(pNew);
1088 return rc;
1089}
1090
1091
1092#ifdef VBOXNETFLT_STATIC_CONFIG
1093/**
1094 * Searches for the NetFlt instance by its name and creates the new one if not found.
1095 *
1096 * @returns VBox status code.
1097 * @retval VINF_SUCCESS and *ppInstance if a new instance was created.
1098 * @retval VINF_ALREADY_INITIALIZED and *ppInstance if an instance already exists.
1099 *
1100 * @param pGlobal Pointer to the globals.
1101 * @param pszName The instance name.
1102 * @param ppInstance Where to return the instance pointer on success.
1103 * @param pvContext Context which needs to be passed along to vboxNetFltOsInitInstance.
1104 */
1105DECLHIDDEN(int) vboxNetFltSearchCreateInstance(PVBOXNETFLTGLOBALS pGlobals, const char *pszName, PVBOXNETFLTINS *ppInstance, void *pvContext)
1106{
1107 PINTNETTRUNKIFPORT pIfPort;
1108 PVBOXNETFLTINS pCur;
1109 VBOXNETFTLINSSTATE enmState;
1110 int rc;
1111
1112 *ppInstance = NULL;
1113 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1114 AssertRCReturn(rc, rc);
1115
1116 /*
1117 * Look for an existing instance in the list.
1118 *
1119 * There might be an existing one in the list if the driver was unbound
1120 * while it was connected to an internal network. We're running into
1121 * a destruction race that is a bit similar to the one in
1122 * vboxNetFltFactoryCreateAndConnect, only the roles are reversed
1123 * and we're not in a position to back down. Instead of backing down
1124 * we'll delay a bit giving the other thread time to complete the
1125 * destructor.
1126 */
1127 pCur = vboxNetFltFindInstanceLocked(pGlobals, pszName);
1128 while (pCur)
1129 {
1130 uint32_t cRefs = ASMAtomicIncU32(&pCur->cRefs);
1131 if (cRefs > 1)
1132 {
1133 enmState = vboxNetFltGetState(pCur);
1134 switch (enmState)
1135 {
1136 case kVBoxNetFltInsState_Unconnected:
1137 case kVBoxNetFltInsState_Connected:
1138 case kVBoxNetFltInsState_Disconnecting:
1139 if (pCur->fDisconnectedFromHost)
1140 {
1141 /* Wait for it to exit the transitional disconnecting
1142 state. It might otherwise be running the risk of
1143 upsetting the OS specific code... */
1144 /** @todo This reconnect stuff should be serialized correctly for static
1145 * devices. Shouldn't it? In the dynamic case we're using the INTNET
1146 * outbound thunk lock, but that doesn't quite cut it here, or does
1147 * it? We could either transition to initializing or make a callback
1148 * while owning the mutex here... */
1149 if (enmState == kVBoxNetFltInsState_Disconnecting)
1150 {
1151 do
1152 {
1153 RTSemFastMutexRelease(pGlobals->hFastMtx);
1154 RTThreadSleep(2); /* (2ms) */
1155 RTSemFastMutexRequest(pGlobals->hFastMtx);
1156 enmState = vboxNetFltGetState(pCur);
1157 }
1158 while (enmState == kVBoxNetFltInsState_Disconnecting);
1159 AssertMsg(enmState == kVBoxNetFltInsState_Unconnected, ("%d\n", enmState));
1160 Assert(pCur->fDisconnectedFromHost);
1161 }
1162
1163 RTSemFastMutexRelease(pGlobals->hFastMtx);
1164 *ppInstance = pCur;
1165 return VINF_ALREADY_INITIALIZED;
1166 }
1167 /* fall thru */
1168
1169 default:
1170 {
1171 bool fDfH = pCur->fDisconnectedFromHost;
1172 RTSemFastMutexRelease(pGlobals->hFastMtx);
1173 vboxNetFltRelease(pCur, false /* fBusy */);
1174 LogRel(("VBoxNetFlt: Huh? An instance of '%s' already exists! [pCur=%p cRefs=%d fDfH=%RTbool enmState=%d]\n",
1175 pszName, pCur, cRefs - 1, fDfH, enmState));
1176 *ppInstance = NULL;
1177 return VERR_INTNET_FLT_IF_BUSY;
1178 }
1179 }
1180 }
1181
1182 /* Zero references, it's being destroyed. Delay a bit so the destructor
1183 can finish its work and try again. (vboxNetFltNewInstance will fail
1184 with duplicate name if we don't.) */
1185# ifdef RT_STRICT
1186 Assert(cRefs == 1);
1187 enmState = vboxNetFltGetState(pCur);
1188 AssertMsg( enmState == kVBoxNetFltInsState_Unconnected
1189 || enmState == kVBoxNetFltInsState_Disconnecting
1190 || enmState == kVBoxNetFltInsState_Destroyed, ("%d\n", enmState));
1191# endif
1192 ASMAtomicDecU32(&pCur->cRefs);
1193 RTSemFastMutexRelease(pGlobals->hFastMtx);
1194 RTThreadSleep(2); /* (2ms) */
1195 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1196 AssertRCReturn(rc, rc);
1197
1198 /* try again */
1199 pCur = vboxNetFltFindInstanceLocked(pGlobals, pszName);
1200 }
1201
1202 RTSemFastMutexRelease(pGlobals->hFastMtx);
1203
1204 /*
1205 * Try create a new instance.
1206 * (fNoPromisc is overridden in the vboxNetFltFactoryCreateAndConnect path, so pass true here.)
1207 */
1208 rc = vboxNetFltNewInstance(pGlobals, pszName, NULL, true /* fNoPromisc */, pvContext, &pIfPort);
1209 if (RT_SUCCESS(rc))
1210 *ppInstance = IFPORT_2_VBOXNETFLTINS(pIfPort);
1211 else
1212 *ppInstance = NULL;
1213
1214 return rc;
1215}
1216#endif /* VBOXNETFLT_STATIC_CONFIG */
1217
1218
1219/**
1220 * @copydoc INTNETTRUNKFACTORY::pfnCreateAndConnect
1221 */
1222static DECLCALLBACK(int) vboxNetFltFactoryCreateAndConnect(PINTNETTRUNKFACTORY pIfFactory, const char *pszName,
1223 PINTNETTRUNKSWPORT pSwitchPort, uint32_t fFlags,
1224 PINTNETTRUNKIFPORT *ppIfPort)
1225{
1226 PVBOXNETFLTGLOBALS pGlobals = (PVBOXNETFLTGLOBALS)((uint8_t *)pIfFactory - RT_OFFSETOF(VBOXNETFLTGLOBALS, TrunkFactory));
1227 PVBOXNETFLTINS pCur;
1228 int rc;
1229
1230 LogFlow(("vboxNetFltFactoryCreateAndConnect: pszName=%p:{%s} fFlags=%#x\n", pszName, pszName, fFlags));
1231 Assert(pGlobals->cFactoryRefs > 0);
1232 AssertMsgReturn(!(fFlags & ~(INTNETTRUNKFACTORY_FLAG_NO_PROMISC)),
1233 ("%#x\n", fFlags), VERR_INVALID_PARAMETER);
1234
1235 /*
1236 * Static: Find instance, check if busy, connect if not.
1237 * Dynamic: Check for duplicate / busy interface instance.
1238 */
1239 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1240 AssertRCReturn(rc, rc);
1241
1242//#if defined(VBOXNETADP) && defined(RT_OS_WINDOWS)
1243// /* temporary hack to pick up the first adapter */
1244// pCur = pGlobals->pInstanceHead; /** @todo Don't for get to remove this temporary hack... :-) */
1245//#else
1246 pCur = vboxNetFltFindInstanceLocked(pGlobals, pszName);
1247//#endif
1248 if (pCur)
1249 {
1250#ifdef VBOXNETFLT_STATIC_CONFIG
1251 /* Try grab a reference. If the count had already reached zero we're racing the
1252 destructor code and must back down. */
1253 uint32_t cRefs = ASMAtomicIncU32(&pCur->cRefs);
1254 if (cRefs > 1)
1255 {
1256 if (vboxNetFltGetState(pCur) == kVBoxNetFltInsState_Unconnected)
1257 {
1258 pCur->enmTrunkState = INTNETTRUNKIFSTATE_INACTIVE; /** @todo protect me? */
1259 pCur->fDisablePromiscuous = !!(fFlags & INTNETTRUNKFACTORY_FLAG_NO_PROMISC);
1260 rc = vboxNetFltConnectIt(pCur, pSwitchPort, ppIfPort);
1261 if (RT_SUCCESS(rc))
1262 pCur = NULL; /* Don't release it, reference given to the caller. */
1263 else
1264 pCur->enmTrunkState = INTNETTRUNKIFSTATE_DISCONNECTING;
1265 }
1266 else
1267 rc = VERR_INTNET_FLT_IF_BUSY;
1268 }
1269 else
1270 {
1271 Assert(cRefs == 1);
1272 ASMAtomicDecU32(&pCur->cRefs);
1273 pCur = NULL; /* nothing to release */
1274 rc = VERR_INTNET_FLT_IF_NOT_FOUND;
1275 }
1276
1277 RTSemFastMutexRelease(pGlobals->hFastMtx);
1278 if (pCur)
1279 vboxNetFltRelease(pCur, false /* fBusy */);
1280#else
1281 rc = VERR_INTNET_FLT_IF_BUSY;
1282 RTSemFastMutexRelease(pGlobals->hFastMtx);
1283#endif
1284 LogFlow(("vboxNetFltFactoryCreateAndConnect: returns %Rrc\n", rc));
1285 return rc;
1286 }
1287
1288 RTSemFastMutexRelease(pGlobals->hFastMtx);
1289
1290#ifdef VBOXNETFLT_STATIC_CONFIG
1291 rc = VERR_INTNET_FLT_IF_NOT_FOUND;
1292#else
1293 /*
1294 * Dynamically create a new instance.
1295 */
1296 rc = vboxNetFltNewInstance(pGlobals,
1297 pszName,
1298 pSwitchPort,
1299 !!(fFlags & INTNETTRUNKFACTORY_FLAG_NO_PROMISC),
1300 NULL,
1301 ppIfPort);
1302#endif
1303 LogFlow(("vboxNetFltFactoryCreateAndConnect: returns %Rrc\n", rc));
1304 return rc;
1305}
1306
1307
1308/**
1309 * @copydoc INTNETTRUNKFACTORY::pfnRelease
1310 */
1311static DECLCALLBACK(void) vboxNetFltFactoryRelease(PINTNETTRUNKFACTORY pIfFactory)
1312{
1313 PVBOXNETFLTGLOBALS pGlobals = (PVBOXNETFLTGLOBALS)((uint8_t *)pIfFactory - RT_OFFSETOF(VBOXNETFLTGLOBALS, TrunkFactory));
1314
1315 int32_t cRefs = ASMAtomicDecS32(&pGlobals->cFactoryRefs);
1316 Assert(cRefs >= 0); NOREF(cRefs);
1317 LogFlow(("vboxNetFltFactoryRelease: cRefs=%d (new)\n", cRefs));
1318}
1319
1320
1321/**
1322 * Implements the SUPDRV component factor interface query method.
1323 *
1324 * @returns Pointer to an interface. NULL if not supported.
1325 *
1326 * @param pSupDrvFactory Pointer to the component factory registration structure.
1327 * @param pSession The session - unused.
1328 * @param pszInterfaceUuid The factory interface id.
1329 */
1330static DECLCALLBACK(void *) vboxNetFltQueryFactoryInterface(PCSUPDRVFACTORY pSupDrvFactory, PSUPDRVSESSION pSession, const char *pszInterfaceUuid)
1331{
1332 PVBOXNETFLTGLOBALS pGlobals = (PVBOXNETFLTGLOBALS)((uint8_t *)pSupDrvFactory - RT_OFFSETOF(VBOXNETFLTGLOBALS, SupDrvFactory));
1333
1334 /*
1335 * Convert the UUID strings and compare them.
1336 */
1337 RTUUID UuidReq;
1338 int rc = RTUuidFromStr(&UuidReq, pszInterfaceUuid);
1339 if (RT_SUCCESS(rc))
1340 {
1341 if (!RTUuidCompareStr(&UuidReq, INTNETTRUNKFACTORY_UUID_STR))
1342 {
1343 ASMAtomicIncS32(&pGlobals->cFactoryRefs);
1344 return &pGlobals->TrunkFactory;
1345 }
1346#ifdef LOG_ENABLED
1347 /* log legacy queries */
1348 /* else if (!RTUuidCompareStr(&UuidReq, INTNETTRUNKFACTORY_V1_UUID_STR))
1349 Log(("VBoxNetFlt: V1 factory query\n"));
1350 */
1351 else
1352 Log(("VBoxNetFlt: unknown factory interface query (%s)\n", pszInterfaceUuid));
1353#endif
1354 }
1355 else
1356 Log(("VBoxNetFlt: rc=%Rrc, uuid=%s\n", rc, pszInterfaceUuid));
1357
1358 return NULL;
1359}
1360
1361
1362/**
1363 * Checks whether the VBoxNetFlt wossname can be unloaded.
1364 *
1365 * This will return false if someone is currently using the module.
1366 *
1367 * @returns true if it's relatively safe to unload it, otherwise false.
1368 * @param pGlobals Pointer to the globals.
1369 */
1370DECLHIDDEN(bool) vboxNetFltCanUnload(PVBOXNETFLTGLOBALS pGlobals)
1371{
1372 int rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1373 bool fRc = !pGlobals->pInstanceHead
1374 && pGlobals->cFactoryRefs <= 0;
1375 RTSemFastMutexRelease(pGlobals->hFastMtx);
1376 AssertRC(rc);
1377 return fRc;
1378}
1379
1380
1381/**
1382 * Try to close the IDC connection to SUPDRV if established.
1383 *
1384 * @returns VBox status code.
1385 * @retval VINF_SUCCESS on success.
1386 * @retval VERR_WRONG_ORDER if we're busy.
1387 *
1388 * @param pGlobals Pointer to the globals.
1389 *
1390 * @sa vboxNetFltTryDeleteIdcAndGlobals()
1391 */
1392DECLHIDDEN(int) vboxNetFltTryDeleteIdc(PVBOXNETFLTGLOBALS pGlobals)
1393{
1394 int rc;
1395
1396 Assert(pGlobals->hFastMtx != NIL_RTSEMFASTMUTEX);
1397
1398 /*
1399 * Check before trying to deregister the factory.
1400 */
1401 if (!vboxNetFltCanUnload(pGlobals))
1402 return VERR_WRONG_ORDER;
1403
1404 if (!pGlobals->fIDCOpen)
1405 rc = VINF_SUCCESS;
1406 else
1407 {
1408 /*
1409 * Disconnect from SUPDRV and check that nobody raced us,
1410 * reconnect if that should happen.
1411 */
1412 rc = SUPR0IdcComponentDeregisterFactory(&pGlobals->SupDrvIDC, &pGlobals->SupDrvFactory);
1413 AssertRC(rc);
1414 if (!vboxNetFltCanUnload(pGlobals))
1415 {
1416 rc = SUPR0IdcComponentRegisterFactory(&pGlobals->SupDrvIDC, &pGlobals->SupDrvFactory);
1417 AssertRC(rc);
1418 return VERR_WRONG_ORDER;
1419 }
1420
1421 SUPR0IdcClose(&pGlobals->SupDrvIDC);
1422 pGlobals->fIDCOpen = false;
1423 }
1424
1425 return rc;
1426}
1427
1428
1429/**
1430 * Establishes the IDC connection to SUPDRV and registers our component factory.
1431 *
1432 * @returns VBox status code.
1433 * @param pGlobals Pointer to the globals.
1434 * @sa vboxNetFltInitGlobalsAndIdc().
1435 */
1436DECLHIDDEN(int) vboxNetFltInitIdc(PVBOXNETFLTGLOBALS pGlobals)
1437{
1438 int rc;
1439 Assert(!pGlobals->fIDCOpen);
1440
1441 /*
1442 * Establish a connection to SUPDRV and register our component factory.
1443 */
1444 rc = SUPR0IdcOpen(&pGlobals->SupDrvIDC, 0 /* iReqVersion = default */, 0 /* iMinVersion = default */, NULL, NULL, NULL);
1445 if (RT_SUCCESS(rc))
1446 {
1447 rc = SUPR0IdcComponentRegisterFactory(&pGlobals->SupDrvIDC, &pGlobals->SupDrvFactory);
1448 if (RT_SUCCESS(rc))
1449 {
1450 pGlobals->fIDCOpen = true;
1451 Log(("VBoxNetFlt: pSession=%p\n", SUPR0IdcGetSession(&pGlobals->SupDrvIDC)));
1452 return rc;
1453 }
1454
1455 /* bail out. */
1456 LogRel(("VBoxNetFlt: Failed to register component factory, rc=%Rrc\n", rc));
1457 SUPR0IdcClose(&pGlobals->SupDrvIDC);
1458 }
1459
1460 return rc;
1461}
1462
1463
1464/**
1465 * Deletes the globals.
1466 *
1467 * This must be called after the IDC connection has been closed,
1468 * see vboxNetFltTryDeleteIdc().
1469 *
1470 * @param pGlobals Pointer to the globals.
1471 * @sa vboxNetFltTryDeleteIdcAndGlobals()
1472 */
1473DECLHIDDEN(void) vboxNetFltDeleteGlobals(PVBOXNETFLTGLOBALS pGlobals)
1474{
1475 Assert(!pGlobals->fIDCOpen);
1476
1477 /*
1478 * Release resources.
1479 */
1480 RTSemFastMutexDestroy(pGlobals->hFastMtx);
1481 pGlobals->hFastMtx = NIL_RTSEMFASTMUTEX;
1482}
1483
1484
1485/**
1486 * Initializes the globals.
1487 *
1488 * @returns VBox status code.
1489 * @param pGlobals Pointer to the globals.
1490 * @sa vboxNetFltInitGlobalsAndIdc().
1491 */
1492DECLHIDDEN(int) vboxNetFltInitGlobals(PVBOXNETFLTGLOBALS pGlobals)
1493{
1494 /*
1495 * Initialize the common portions of the structure.
1496 */
1497 int rc = RTSemFastMutexCreate(&pGlobals->hFastMtx);
1498 if (RT_SUCCESS(rc))
1499 {
1500 pGlobals->pInstanceHead = NULL;
1501
1502 pGlobals->TrunkFactory.pfnRelease = vboxNetFltFactoryRelease;
1503 pGlobals->TrunkFactory.pfnCreateAndConnect = vboxNetFltFactoryCreateAndConnect;
1504#if defined(RT_OS_WINDOWS) && defined(VBOXNETADP)
1505 memcpy(pGlobals->SupDrvFactory.szName, "VBoxNetAdp", sizeof("VBoxNetAdp"));
1506#else
1507 memcpy(pGlobals->SupDrvFactory.szName, "VBoxNetFlt", sizeof("VBoxNetFlt"));
1508#endif
1509 pGlobals->SupDrvFactory.pfnQueryFactoryInterface = vboxNetFltQueryFactoryInterface;
1510 pGlobals->fIDCOpen = false;
1511
1512 return rc;
1513 }
1514
1515 return rc;
1516}
1517
1518
1519/**
1520 * Called by the native part when the OS wants the driver to unload.
1521 *
1522 * @returns VINF_SUCCESS on success, VERR_WRONG_ORDER if we're busy.
1523 *
1524 * @param pGlobals Pointer to the globals.
1525 */
1526DECLHIDDEN(int) vboxNetFltTryDeleteIdcAndGlobals(PVBOXNETFLTGLOBALS pGlobals)
1527{
1528 int rc = vboxNetFltTryDeleteIdc(pGlobals);
1529 if (RT_SUCCESS(rc))
1530 vboxNetFltDeleteGlobals(pGlobals);
1531 return rc;
1532}
1533
1534
1535/**
1536 * Called by the native driver/kext module initialization routine.
1537 *
1538 * It will initialize the common parts of the globals, assuming the caller
1539 * has already taken care of the OS specific bits, and establish the IDC
1540 * connection to SUPDRV.
1541 *
1542 * @returns VBox status code.
1543 * @param pGlobals Pointer to the globals.
1544 */
1545DECLHIDDEN(int) vboxNetFltInitGlobalsAndIdc(PVBOXNETFLTGLOBALS pGlobals)
1546{
1547 /*
1548 * Initialize the common portions of the structure.
1549 */
1550 int rc = vboxNetFltInitGlobals(pGlobals);
1551 if (RT_SUCCESS(rc))
1552 {
1553 rc = vboxNetFltInitIdc(pGlobals);
1554 if (RT_SUCCESS(rc))
1555 return rc;
1556
1557 /* bail out. */
1558 vboxNetFltDeleteGlobals(pGlobals);
1559 }
1560
1561 return rc;
1562}
1563
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