VirtualBox

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

Last change on this file since 29108 was 28829, checked in by vboxsync, 15 years ago

vboxNetFltMaybeRediscovered: Don't do rediscovery with preemption disabled.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 52.7 KB
Line 
1/* $Id: VBoxNetFlt.c 28829 2010-04-27 14:05:08Z 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 preemptioni
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, 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, 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::pfnDisconnectAndRelease
538 */
539static DECLCALLBACK(void) vboxNetFltPortDisconnectAndRelease(PINTNETTRUNKIFPORT pIfPort)
540{
541 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
542 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
543
544 /*
545 * Serious paranoia.
546 */
547 AssertPtr(pThis);
548 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
549 Assert(pThis->MyPort.u32VersionEnd == INTNETTRUNKIFPORT_VERSION);
550 AssertPtr(pThis->pGlobals);
551 Assert(pThis->hEventIdle != NIL_RTSEMEVENT);
552 Assert(pThis->hSpinlock != NIL_RTSPINLOCK);
553 Assert(pThis->szName[0]);
554
555 Assert(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Connected);
556 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_DISCONNECTING);
557 Assert(!pThis->fRediscoveryPending);
558 Assert(!pThis->cBusy);
559
560 /*
561 * Disconnect and release it.
562 */
563 RTSpinlockAcquireNoInts(pThis->hSpinlock, &Tmp);
564 vboxNetFltSetState(pThis, kVBoxNetFltInsState_Disconnecting);
565 RTSpinlockReleaseNoInts(pThis->hSpinlock, &Tmp);
566
567 vboxNetFltOsDisconnectIt(pThis);
568 pThis->pSwitchPort = NULL;
569
570#ifdef VBOXNETFLT_STATIC_CONFIG
571 RTSpinlockAcquireNoInts(pThis->hSpinlock, &Tmp);
572 vboxNetFltSetState(pThis, kVBoxNetFltInsState_Unconnected);
573 RTSpinlockReleaseNoInts(pThis->hSpinlock, &Tmp);
574#endif
575
576 vboxNetFltRelease(pThis, false /* fBusy */);
577}
578
579
580/**
581 * Destroy a device that has been disconnected from the switch.
582 *
583 * @returns true if the instance is destroyed, false otherwise.
584 * @param pThis The instance to be destroyed. This is
585 * no longer valid when this function returns.
586 */
587static bool vboxNetFltDestroyInstance(PVBOXNETFLTINS pThis)
588{
589 PVBOXNETFLTGLOBALS pGlobals = pThis->pGlobals;
590 uint32_t cRefs = ASMAtomicUoReadU32((uint32_t volatile *)&pThis->cRefs);
591 int rc;
592 LogFlow(("vboxNetFltDestroyInstance: pThis=%p (%s)\n", pThis, pThis->szName));
593
594 /*
595 * Validate the state.
596 */
597#ifdef VBOXNETFLT_STATIC_CONFIG
598 Assert( vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Disconnecting
599 || vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Unconnected);
600#else
601 Assert(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Disconnecting);
602#endif
603 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_DISCONNECTING);
604 Assert(!pThis->fRediscoveryPending);
605 Assert(!pThis->cRefs);
606 Assert(!pThis->cBusy);
607 Assert(!pThis->pSwitchPort);
608
609 /*
610 * Make sure the state is 'disconnecting' / 'destroying' and let the OS
611 * specific code do its part of the cleanup outside the mutex.
612 */
613 rc = RTSemFastMutexRequest(pGlobals->hFastMtx); AssertRC(rc);
614 vboxNetFltSetState(pThis, kVBoxNetFltInsState_Disconnecting);
615 RTSemFastMutexRelease(pGlobals->hFastMtx);
616
617 vboxNetFltOsDeleteInstance(pThis);
618
619 /*
620 * Unlink the instance and free up its resources.
621 */
622 rc = RTSemFastMutexRequest(pGlobals->hFastMtx); AssertRC(rc);
623 vboxNetFltSetState(pThis, kVBoxNetFltInsState_Destroyed);
624 vboxNetFltUnlinkLocked(pGlobals, pThis);
625 RTSemFastMutexRelease(pGlobals->hFastMtx);
626
627 RTSemEventDestroy(pThis->hEventIdle);
628 pThis->hEventIdle = NIL_RTSEMEVENT;
629 RTSpinlockDestroy(pThis->hSpinlock);
630 pThis->hSpinlock = NIL_RTSPINLOCK;
631 RTMemFree(pThis);
632
633 NOREF(cRefs);
634
635 return true;
636}
637
638
639/**
640 * Releases a reference to the specified instance.
641 *
642 * This method will destroy the instance when the count reaches 0.
643 * It will also take care of decrementing the counter and idle wakeup.
644 *
645 * @param pThis The instance.
646 * @param fBusy Whether the busy counter should be decremented too.
647 */
648DECLHIDDEN(void) vboxNetFltRelease(PVBOXNETFLTINS pThis, bool fBusy)
649{
650 uint32_t cRefs;
651
652 /*
653 * Paranoid Android.
654 */
655 AssertPtr(pThis);
656 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
657 Assert(pThis->MyPort.u32VersionEnd == INTNETTRUNKIFPORT_VERSION);
658 Assert( vboxNetFltGetState(pThis) > kVBoxNetFltInsState_Invalid
659 && vboxNetFltGetState(pThis) < kVBoxNetFltInsState_Destroyed);
660 AssertPtr(pThis->pGlobals);
661 Assert(pThis->hEventIdle != NIL_RTSEMEVENT);
662 Assert(pThis->hSpinlock != NIL_RTSPINLOCK);
663 Assert(pThis->szName[0]);
664
665 /*
666 * Work the busy counter.
667 */
668 if (fBusy)
669 {
670 cRefs = ASMAtomicDecU32(&pThis->cBusy);
671 if (!cRefs)
672 {
673 int rc = RTSemEventSignal(pThis->hEventIdle);
674 AssertRC(rc);
675 }
676 else
677 Assert(cRefs < UINT32_MAX / 2);
678 }
679
680 /*
681 * The object reference counting.
682 */
683 cRefs = ASMAtomicDecU32(&pThis->cRefs);
684 if (!cRefs)
685 vboxNetFltDestroyInstance(pThis);
686 else
687 Assert(cRefs < UINT32_MAX / 2);
688}
689
690
691/**
692 * @copydoc INTNETTRUNKIFPORT::pfnRetain
693 */
694static DECLCALLBACK(void) vboxNetFltPortRelease(PINTNETTRUNKIFPORT pIfPort)
695{
696 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
697 vboxNetFltRelease(pThis, false /* fBusy */);
698}
699
700
701/**
702 * Retains a reference to the specified instance and a busy reference too.
703 *
704 * @param pThis The instance.
705 * @param fBusy Whether the busy counter should be incremented as well.
706 */
707DECLHIDDEN(void) vboxNetFltRetain(PVBOXNETFLTINS pThis, bool fBusy)
708{
709 uint32_t cRefs;
710
711 /*
712 * Paranoid Android.
713 */
714 AssertPtr(pThis);
715 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
716 Assert(pThis->MyPort.u32VersionEnd == INTNETTRUNKIFPORT_VERSION);
717 Assert( vboxNetFltGetState(pThis) > kVBoxNetFltInsState_Invalid
718 && vboxNetFltGetState(pThis) < kVBoxNetFltInsState_Destroyed);
719 AssertPtr(pThis->pGlobals);
720 Assert(pThis->hEventIdle != NIL_RTSEMEVENT);
721 Assert(pThis->hSpinlock != NIL_RTSPINLOCK);
722 Assert(pThis->szName[0]);
723
724 /*
725 * Retain the object.
726 */
727 cRefs = ASMAtomicIncU32(&pThis->cRefs);
728 Assert(cRefs > 1 && cRefs < UINT32_MAX / 2);
729
730 /*
731 * Work the busy counter.
732 */
733 if (fBusy)
734 {
735 cRefs = ASMAtomicIncU32(&pThis->cBusy);
736 Assert(cRefs > 0 && cRefs < UINT32_MAX / 2);
737 }
738
739 NOREF(cRefs);
740}
741
742
743/**
744 * Tries to retain the device as busy if the trunk is active.
745 *
746 * This is used before calling pfnRecv or pfnPreRecv.
747 *
748 * @returns true if we succeeded in retaining a busy reference to the active
749 * device. false if we failed.
750 * @param pThis The instance.
751 */
752DECLHIDDEN(bool) vboxNetFltTryRetainBusyActive(PVBOXNETFLTINS pThis)
753{
754 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
755 uint32_t cRefs;
756 bool fRc;
757
758 /*
759 * Paranoid Android.
760 */
761 AssertPtr(pThis);
762 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
763 Assert(pThis->MyPort.u32VersionEnd == INTNETTRUNKIFPORT_VERSION);
764 Assert( vboxNetFltGetState(pThis) > kVBoxNetFltInsState_Invalid
765 && vboxNetFltGetState(pThis) < kVBoxNetFltInsState_Destroyed);
766 AssertPtr(pThis->pGlobals);
767 Assert(pThis->hEventIdle != NIL_RTSEMEVENT);
768 Assert(pThis->hSpinlock != NIL_RTSPINLOCK);
769 Assert(pThis->szName[0]);
770
771 /*
772 * Do the retaining and checking behind the spinlock.
773 */
774 RTSpinlockAcquireNoInts(pThis->hSpinlock, &Tmp);
775 fRc = pThis->enmTrunkState == INTNETTRUNKIFSTATE_ACTIVE;
776 if (fRc)
777 {
778 cRefs = ASMAtomicIncU32(&pThis->cRefs);
779 AssertMsg(cRefs > 1 && cRefs < UINT32_MAX / 2, ("%d\n", cRefs)); NOREF(cRefs);
780
781 cRefs = ASMAtomicIncU32(&pThis->cBusy);
782 AssertMsg(cRefs >= 1 && cRefs < UINT32_MAX / 2, ("%d\n", cRefs)); NOREF(cRefs);
783 }
784 RTSpinlockReleaseNoInts(pThis->hSpinlock, &Tmp);
785
786 return fRc;
787}
788
789
790/**
791 * Tries to retain the device as busy if the trunk is not disconnecting.
792 *
793 * This is used before reporting stuff to the internal network.
794 *
795 * @returns true if we succeeded in retaining a busy reference to the active
796 * device. false if we failed.
797 * @param pThis The instance.
798 */
799DECLHIDDEN(bool) vboxNetFltTryRetainBusyNotDisconnected(PVBOXNETFLTINS pThis)
800{
801 RTSPINLOCKTMP Tmp = RTSPINLOCKTMP_INITIALIZER;
802 uint32_t cRefs;
803 bool fRc;
804
805 /*
806 * Paranoid Android.
807 */
808 AssertPtr(pThis);
809 Assert(pThis->MyPort.u32Version == INTNETTRUNKIFPORT_VERSION);
810 Assert(pThis->MyPort.u32VersionEnd == INTNETTRUNKIFPORT_VERSION);
811 Assert( vboxNetFltGetState(pThis) > kVBoxNetFltInsState_Invalid
812 && vboxNetFltGetState(pThis) < kVBoxNetFltInsState_Destroyed);
813 AssertPtr(pThis->pGlobals);
814 Assert(pThis->hEventIdle != NIL_RTSEMEVENT);
815 Assert(pThis->hSpinlock != NIL_RTSPINLOCK);
816 Assert(pThis->szName[0]);
817
818 /*
819 * Do the retaining and checking behind the spinlock.
820 */
821 RTSpinlockAcquireNoInts(pThis->hSpinlock, &Tmp);
822 fRc = pThis->enmTrunkState == INTNETTRUNKIFSTATE_ACTIVE
823 || pThis->enmTrunkState == INTNETTRUNKIFSTATE_INACTIVE;
824 if (fRc)
825 {
826 cRefs = ASMAtomicIncU32(&pThis->cRefs);
827 AssertMsg(cRefs > 1 && cRefs < UINT32_MAX / 2, ("%d\n", cRefs)); NOREF(cRefs);
828
829 cRefs = ASMAtomicIncU32(&pThis->cBusy);
830 AssertMsg(cRefs >= 1 && cRefs < UINT32_MAX / 2, ("%d\n", cRefs)); NOREF(cRefs);
831 }
832 RTSpinlockReleaseNoInts(pThis->hSpinlock, &Tmp);
833
834 return fRc;
835}
836
837
838/**
839 * @copydoc INTNETTRUNKIFPORT::pfnRetain
840 */
841static DECLCALLBACK(void) vboxNetFltPortRetain(PINTNETTRUNKIFPORT pIfPort)
842{
843 PVBOXNETFLTINS pThis = IFPORT_2_VBOXNETFLTINS(pIfPort);
844 vboxNetFltRetain(pThis, false /* fBusy */);
845}
846
847
848/**
849 * Connects the instance to the specified switch port.
850 *
851 * Called while owning the lock. We're ASSUMING that the internal
852 * networking code is already owning an recursive mutex, so, there
853 * will be no deadlocks when vboxNetFltOsConnectIt calls back into
854 * it for setting preferences.
855 *
856 * @returns VBox status code.
857 * @param pThis The instance.
858 * @param pSwitchPort The port on the internal network 'switch'.
859 * @param ppIfPort Where to return our port interface.
860 */
861static int vboxNetFltConnectIt(PVBOXNETFLTINS pThis, PINTNETTRUNKSWPORT pSwitchPort, PINTNETTRUNKIFPORT *ppIfPort)
862{
863 int rc;
864
865 /*
866 * Validate state.
867 */
868 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_INACTIVE);
869 Assert(!pThis->fRediscoveryPending);
870 Assert(!pThis->cBusy);
871#ifdef VBOXNETFLT_STATIC_CONFIG
872 Assert(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Unconnected);
873#else
874 Assert(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Initializing);
875#endif
876
877 /*
878 * Do the job.
879 * Note that we're calling the os stuff while owning the semaphore here.
880 */
881 pThis->pSwitchPort = pSwitchPort;
882 rc = vboxNetFltOsConnectIt(pThis);
883 if (RT_SUCCESS(rc))
884 {
885 vboxNetFltSetState(pThis, kVBoxNetFltInsState_Connected);
886 *ppIfPort = &pThis->MyPort;
887 }
888 else
889 pThis->pSwitchPort = NULL;
890
891 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_INACTIVE);
892 return rc;
893}
894
895
896/**
897 * Creates a new instance.
898 *
899 * The new instance will be in the suspended state in a dynamic config and in
900 * the inactive in a static one.
901 *
902 * Called without owning the lock, but will request is several times.
903 *
904 * @returns VBox status code.
905 * @param pGlobals The globals.
906 * @param pszName The instance name.
907 * @param pSwitchPort The port on the switch that we're connected with (dynamic only).
908 * @param fNoPromisc Do not attempt going into promiscuous mode.
909 * @param pvContext Context argument for vboxNetFltOsInitInstance.
910 * @param ppIfPort Where to store the pointer to our port interface (dynamic only).
911 */
912static int vboxNetFltNewInstance(PVBOXNETFLTGLOBALS pGlobals, const char *pszName, PINTNETTRUNKSWPORT pSwitchPort,
913 bool fNoPromisc, void *pvContext, PINTNETTRUNKIFPORT *ppIfPort)
914{
915 /*
916 * Allocate and initialize a new instance before requesting the mutex.
917 */
918 int rc;
919 size_t const cchName = strlen(pszName);
920 PVBOXNETFLTINS pNew = (PVBOXNETFLTINS)RTMemAllocZ(RT_OFFSETOF(VBOXNETFLTINS, szName[cchName + 1]));
921 if (!pNew)
922 return VERR_INTNET_FLT_IF_FAILED;
923 pNew->pNext = NULL;
924 pNew->MyPort.u32Version = INTNETTRUNKIFPORT_VERSION;
925 pNew->MyPort.pfnRetain = vboxNetFltPortRetain;
926 pNew->MyPort.pfnRelease = vboxNetFltPortRelease;
927 pNew->MyPort.pfnDisconnectAndRelease= vboxNetFltPortDisconnectAndRelease;
928 pNew->MyPort.pfnSetState = vboxNetFltPortSetState;
929 pNew->MyPort.pfnWaitForIdle = vboxNetFltPortWaitForIdle;
930 pNew->MyPort.pfnXmit = vboxNetFltPortXmit;
931 pNew->MyPort.u32VersionEnd = INTNETTRUNKIFPORT_VERSION;
932 pNew->pSwitchPort = pSwitchPort;
933 pNew->pGlobals = pGlobals;
934 pNew->hSpinlock = NIL_RTSPINLOCK;
935 pNew->enmState = kVBoxNetFltInsState_Initializing;
936 pNew->enmTrunkState = INTNETTRUNKIFSTATE_INACTIVE;
937 pNew->fDisconnectedFromHost = false;
938 pNew->fRediscoveryPending = false;
939 pNew->fDisablePromiscuous = fNoPromisc;
940 pNew->NanoTSLastRediscovery = INT64_MAX;
941 pNew->cRefs = 1;
942 pNew->cBusy = 0;
943 pNew->hEventIdle = NIL_RTSEMEVENT;
944 memcpy(pNew->szName, pszName, cchName + 1);
945
946 rc = RTSpinlockCreate(&pNew->hSpinlock);
947 if (RT_SUCCESS(rc))
948 {
949 rc = RTSemEventCreate(&pNew->hEventIdle);
950 if (RT_SUCCESS(rc))
951 {
952 rc = vboxNetFltOsPreInitInstance(pNew);
953 if (RT_SUCCESS(rc))
954 {
955 /*
956 * Insert the instance into the chain, checking for
957 * duplicates first of course (race).
958 */
959 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
960 if (RT_SUCCESS(rc))
961 {
962 if (!vboxNetFltFindInstanceLocked(pGlobals, pszName))
963 {
964 pNew->pNext = pGlobals->pInstanceHead;
965 pGlobals->pInstanceHead = pNew;
966 RTSemFastMutexRelease(pGlobals->hFastMtx);
967
968 /*
969 * Call the OS specific initialization code.
970 */
971 rc = vboxNetFltOsInitInstance(pNew, pvContext);
972 RTSemFastMutexRequest(pGlobals->hFastMtx);
973 if (RT_SUCCESS(rc))
974 {
975#ifdef VBOXNETFLT_STATIC_CONFIG
976 /*
977 * Static instances are unconnected at birth.
978 */
979 Assert(!pSwitchPort);
980 pNew->enmState = kVBoxNetFltInsState_Unconnected;
981 RTSemFastMutexRelease(pGlobals->hFastMtx);
982 *ppIfPort = &pNew->MyPort;
983 return rc;
984
985#else /* !VBOXNETFLT_STATIC_CONFIG */
986 /*
987 * Connect it as well, the OS specific bits has to be done outside
988 * the lock as they may call back to into intnet.
989 */
990 rc = vboxNetFltConnectIt(pNew, pSwitchPort, ppIfPort);
991 if (RT_SUCCESS(rc))
992 {
993 RTSemFastMutexRelease(pGlobals->hFastMtx);
994 Assert(*ppIfPort == &pNew->MyPort);
995 return rc;
996 }
997
998 /* Bail out (failed). */
999 vboxNetFltOsDeleteInstance(pNew);
1000#endif /* !VBOXNETFLT_STATIC_CONFIG */
1001 }
1002 vboxNetFltUnlinkLocked(pGlobals, pNew);
1003 }
1004 else
1005 rc = VERR_INTNET_FLT_IF_BUSY;
1006 RTSemFastMutexRelease(pGlobals->hFastMtx);
1007 }
1008 }
1009 RTSemEventDestroy(pNew->hEventIdle);
1010 }
1011 RTSpinlockDestroy(pNew->hSpinlock);
1012 }
1013
1014 RTMemFree(pNew);
1015 return rc;
1016}
1017
1018
1019#ifdef VBOXNETFLT_STATIC_CONFIG
1020/**
1021 * Searches for the NetFlt instance by its name and creates the new one if not found.
1022 *
1023 * @returns VBox status code.
1024 * @retval VINF_SUCCESS and *ppInstance if a new instance was created.
1025 * @retval VINF_ALREADY_INITIALIZED and *ppInstance if an instance already exists.
1026 *
1027 * @param pGlobal Pointer to the globals.
1028 * @param pszName The instance name.
1029 * @param ppInstance Where to return the instance pointer on success.
1030 * @param pvContext Context which needs to be passed along to vboxNetFltOsInitInstance.
1031 */
1032DECLHIDDEN(int) vboxNetFltSearchCreateInstance(PVBOXNETFLTGLOBALS pGlobals, const char *pszName, PVBOXNETFLTINS *ppInstance, void *pvContext)
1033{
1034 PINTNETTRUNKIFPORT pIfPort;
1035 PVBOXNETFLTINS pCur;
1036 VBOXNETFTLINSSTATE enmState;
1037 int rc;
1038
1039 *ppInstance = NULL;
1040 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1041 AssertRCReturn(rc, rc);
1042
1043 /*
1044 * Look for an existing instance in the list.
1045 *
1046 * There might be an existing one in the list if the driver was unbound
1047 * while it was connected to an internal network. We're running into
1048 * a destruction race that is a bit similar to the one in
1049 * vboxNetFltFactoryCreateAndConnect, only the roles are reversed
1050 * and we're not in a position to back down. Instead of backing down
1051 * we'll delay a bit giving the other thread time to complete the
1052 * destructor.
1053 */
1054 pCur = vboxNetFltFindInstanceLocked(pGlobals, pszName);
1055 while (pCur)
1056 {
1057 uint32_t cRefs = ASMAtomicIncU32(&pCur->cRefs);
1058 if (cRefs > 1)
1059 {
1060 enmState = vboxNetFltGetState(pCur);
1061 switch (enmState)
1062 {
1063 case kVBoxNetFltInsState_Unconnected:
1064 case kVBoxNetFltInsState_Connected:
1065 case kVBoxNetFltInsState_Disconnecting:
1066 if (pCur->fDisconnectedFromHost)
1067 {
1068 /* Wait for it to exit the transitional disconnecting
1069 state. It might otherwise be running the risk of
1070 upsetting the OS specific code... */
1071 /** @todo This reconnect stuff should be serialized correctly for static
1072 * devices. Shouldn't it? In the dynamic case we're using the INTNET
1073 * outbound thrunk lock, but that doesn't quite cut it here, or does
1074 * it? We could either transition to initializing or make a callback
1075 * while owning the mutext here... */
1076 if (enmState == kVBoxNetFltInsState_Disconnecting)
1077 {
1078 do
1079 {
1080 RTSemFastMutexRelease(pGlobals->hFastMtx);
1081 RTThreadSleep(2); /* (2ms) */
1082 RTSemFastMutexRequest(pGlobals->hFastMtx);
1083 enmState = vboxNetFltGetState(pCur);
1084 }
1085 while (enmState == kVBoxNetFltInsState_Disconnecting);
1086 AssertMsg(enmState == kVBoxNetFltInsState_Unconnected, ("%d\n", enmState));
1087 Assert(pCur->fDisconnectedFromHost);
1088 }
1089
1090 RTSemFastMutexRelease(pGlobals->hFastMtx);
1091 *ppInstance = pCur;
1092 return VINF_ALREADY_INITIALIZED;
1093 }
1094 /* fall thru */
1095
1096 default:
1097 {
1098 bool fDfH = pCur->fDisconnectedFromHost;
1099 RTSemFastMutexRelease(pGlobals->hFastMtx);
1100 vboxNetFltRelease(pCur, false /* fBusy */);
1101 LogRel(("VBoxNetFlt: Huh? An instance of '%s' already exists! [pCur=%p cRefs=%d fDfH=%RTbool enmState=%d]\n",
1102 pszName, pCur, cRefs - 1, fDfH, enmState));
1103 *ppInstance = NULL;
1104 return VERR_INTNET_FLT_IF_BUSY;
1105 }
1106 }
1107 }
1108
1109 /* Zero references, it's being destroyed. Delay a bit so the destructor
1110 can finish its work and try again. (vboxNetFltNewInstance will fail
1111 with duplicate name if we don't.) */
1112# ifdef RT_STRICT
1113 Assert(cRefs == 1);
1114 enmState = vboxNetFltGetState(pCur);
1115 AssertMsg( enmState == kVBoxNetFltInsState_Unconnected
1116 || enmState == kVBoxNetFltInsState_Disconnecting
1117 || enmState == kVBoxNetFltInsState_Destroyed, ("%d\n", enmState));
1118# endif
1119 ASMAtomicDecU32(&pCur->cRefs);
1120 RTSemFastMutexRelease(pGlobals->hFastMtx);
1121 RTThreadSleep(2); /* (2ms) */
1122 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1123 AssertRCReturn(rc, rc);
1124
1125 /* try again */
1126 pCur = vboxNetFltFindInstanceLocked(pGlobals, pszName);
1127 }
1128
1129 RTSemFastMutexRelease(pGlobals->hFastMtx);
1130
1131 /*
1132 * Try create a new instance.
1133 * (fNoPromisc is overridden in the vboxNetFltFactoryCreateAndConnect path, so pass true here.)
1134 */
1135 rc = vboxNetFltNewInstance(pGlobals, pszName, NULL, true /* fNoPromisc */, pvContext, &pIfPort);
1136 if (RT_SUCCESS(rc))
1137 *ppInstance = IFPORT_2_VBOXNETFLTINS(pIfPort);
1138 else
1139 *ppInstance = NULL;
1140
1141 return rc;
1142}
1143#endif /* VBOXNETFLT_STATIC_CONFIG */
1144
1145
1146/**
1147 * @copydoc INTNETTRUNKFACTORY::pfnCreateAndConnect
1148 */
1149static DECLCALLBACK(int) vboxNetFltFactoryCreateAndConnect(PINTNETTRUNKFACTORY pIfFactory, const char *pszName,
1150 PINTNETTRUNKSWPORT pSwitchPort, uint32_t fFlags,
1151 PINTNETTRUNKIFPORT *ppIfPort)
1152{
1153 PVBOXNETFLTGLOBALS pGlobals = (PVBOXNETFLTGLOBALS)((uint8_t *)pIfFactory - RT_OFFSETOF(VBOXNETFLTGLOBALS, TrunkFactory));
1154 PVBOXNETFLTINS pCur;
1155 int rc;
1156
1157 LogFlow(("vboxNetFltFactoryCreateAndConnect: pszName=%p:{%s} fFlags=%#x\n", pszName, pszName, fFlags));
1158 Assert(pGlobals->cFactoryRefs > 0);
1159 AssertMsgReturn(!(fFlags & ~(INTNETTRUNKFACTORY_FLAG_NO_PROMISC)),
1160 ("%#x\n", fFlags), VERR_INVALID_PARAMETER);
1161
1162 /*
1163 * Static: Find instance, check if busy, connect if not.
1164 * Dynamic: Check for duplicate / busy interface instance.
1165 */
1166 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1167 AssertRCReturn(rc, rc);
1168
1169//#if defined(VBOXNETADP) && defined(RT_OS_WINDOWS)
1170// /* temporary hack to pick up the first adapter */
1171// pCur = pGlobals->pInstanceHead; /** @todo Don't for get to remove this temporary hack... :-) */
1172//#else
1173 pCur = vboxNetFltFindInstanceLocked(pGlobals, pszName);
1174//#endif
1175 if (pCur)
1176 {
1177#ifdef VBOXNETFLT_STATIC_CONFIG
1178 /* Try grab a reference. If the count had already reached zero we're racing the
1179 destructor code and must back down. */
1180 uint32_t cRefs = ASMAtomicIncU32(&pCur->cRefs);
1181 if (cRefs > 1)
1182 {
1183 if (vboxNetFltGetState(pCur) == kVBoxNetFltInsState_Unconnected)
1184 {
1185 pCur->fDisablePromiscuous = !!(fFlags & INTNETTRUNKFACTORY_FLAG_NO_PROMISC);
1186 rc = vboxNetFltConnectIt(pCur, pSwitchPort, ppIfPort);
1187 if (RT_SUCCESS(rc))
1188 pCur = NULL; /* Don't release it, reference given to the caller. */
1189 }
1190 else
1191 rc = VERR_INTNET_FLT_IF_BUSY;
1192 }
1193 else
1194 {
1195 Assert(cRefs == 1);
1196 ASMAtomicDecU32(&pCur->cRefs);
1197 pCur = NULL; /* nothing to release */
1198 rc = VERR_INTNET_FLT_IF_NOT_FOUND;
1199 }
1200
1201 RTSemFastMutexRelease(pGlobals->hFastMtx);
1202 if (pCur)
1203 vboxNetFltRelease(pCur, false /* fBusy */);
1204#else
1205 rc = VERR_INTNET_FLT_IF_BUSY;
1206 RTSemFastMutexRelease(pGlobals->hFastMtx);
1207#endif
1208 LogFlow(("vboxNetFltFactoryCreateAndConnect: returns %Rrc\n", rc));
1209 return rc;
1210 }
1211
1212 RTSemFastMutexRelease(pGlobals->hFastMtx);
1213
1214#ifdef VBOXNETFLT_STATIC_CONFIG
1215 rc = VERR_INTNET_FLT_IF_NOT_FOUND;
1216#else
1217 /*
1218 * Dynamically create a new instance.
1219 */
1220 rc = vboxNetFltNewInstance(pGlobals,
1221 pszName,
1222 pSwitchPort,
1223 !!(fFlags & INTNETTRUNKFACTORY_FLAG_NO_PROMISC),
1224 NULL,
1225 ppIfPort);
1226#endif
1227 LogFlow(("vboxNetFltFactoryCreateAndConnect: returns %Rrc\n", rc));
1228 return rc;
1229}
1230
1231
1232/**
1233 * @copydoc INTNETTRUNKFACTORY::pfnRelease
1234 */
1235static DECLCALLBACK(void) vboxNetFltFactoryRelease(PINTNETTRUNKFACTORY pIfFactory)
1236{
1237 PVBOXNETFLTGLOBALS pGlobals = (PVBOXNETFLTGLOBALS)((uint8_t *)pIfFactory - RT_OFFSETOF(VBOXNETFLTGLOBALS, TrunkFactory));
1238
1239 int32_t cRefs = ASMAtomicDecS32(&pGlobals->cFactoryRefs);
1240 Assert(cRefs >= 0); NOREF(cRefs);
1241 LogFlow(("vboxNetFltFactoryRelease: cRefs=%d (new)\n", cRefs));
1242}
1243
1244
1245/**
1246 * Implements the SUPDRV component factor interface query method.
1247 *
1248 * @returns Pointer to an interface. NULL if not supported.
1249 *
1250 * @param pSupDrvFactory Pointer to the componet factory registration structure.
1251 * @param pSession The session - unused.
1252 * @param pszInterfaceUuid The factory interface id.
1253 */
1254static DECLCALLBACK(void *) vboxNetFltQueryFactoryInterface(PCSUPDRVFACTORY pSupDrvFactory, PSUPDRVSESSION pSession, const char *pszInterfaceUuid)
1255{
1256 PVBOXNETFLTGLOBALS pGlobals = (PVBOXNETFLTGLOBALS)((uint8_t *)pSupDrvFactory - RT_OFFSETOF(VBOXNETFLTGLOBALS, SupDrvFactory));
1257
1258 /*
1259 * Convert the UUID strings and compare them.
1260 */
1261 RTUUID UuidReq;
1262 int rc = RTUuidFromStr(&UuidReq, pszInterfaceUuid);
1263 if (RT_SUCCESS(rc))
1264 {
1265 if (!RTUuidCompareStr(&UuidReq, INTNETTRUNKFACTORY_UUID_STR))
1266 {
1267 ASMAtomicIncS32(&pGlobals->cFactoryRefs);
1268 return &pGlobals->TrunkFactory;
1269 }
1270#ifdef LOG_ENABLED
1271 /* log legacy queries */
1272 /* else if (!RTUuidCompareStr(&UuidReq, INTNETTRUNKFACTORY_V1_UUID_STR))
1273 Log(("VBoxNetFlt: V1 factory query\n"));
1274 */
1275 else
1276 Log(("VBoxNetFlt: unknown factory interface query (%s)\n", pszInterfaceUuid));
1277#endif
1278 }
1279 else
1280 Log(("VBoxNetFlt: rc=%Rrc, uuid=%s\n", rc, pszInterfaceUuid));
1281
1282 return NULL;
1283}
1284
1285
1286/**
1287 * Checks whether the VBoxNetFlt wossname can be unloaded.
1288 *
1289 * This will return false if someone is currently using the module.
1290 *
1291 * @returns true if it's relatively safe to unload it, otherwise false.
1292 * @param pGlobals Pointer to the globals.
1293 */
1294DECLHIDDEN(bool) vboxNetFltCanUnload(PVBOXNETFLTGLOBALS pGlobals)
1295{
1296 int rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1297 bool fRc = !pGlobals->pInstanceHead
1298 && pGlobals->cFactoryRefs <= 0;
1299 RTSemFastMutexRelease(pGlobals->hFastMtx);
1300 AssertRC(rc);
1301 return fRc;
1302}
1303
1304
1305/**
1306 * Try to close the IDC connection to SUPDRV if established.
1307 *
1308 * @returns VBox status code.
1309 * @retval VINF_SUCCESS on success.
1310 * @retval VERR_WRONG_ORDER if we're busy.
1311 *
1312 * @param pGlobals Pointer to the globals.
1313 *
1314 * @sa vboxNetFltTryDeleteIdcAndGlobals()
1315 */
1316DECLHIDDEN(int) vboxNetFltTryDeleteIdc(PVBOXNETFLTGLOBALS pGlobals)
1317{
1318 int rc;
1319
1320 Assert(pGlobals->hFastMtx != NIL_RTSEMFASTMUTEX);
1321
1322 /*
1323 * Check before trying to deregister the factory.
1324 */
1325 if (!vboxNetFltCanUnload(pGlobals))
1326 return VERR_WRONG_ORDER;
1327
1328 if (!pGlobals->fIDCOpen)
1329 rc = VINF_SUCCESS;
1330 else
1331 {
1332 /*
1333 * Disconnect from SUPDRV and check that nobody raced us,
1334 * reconnect if that should happen.
1335 */
1336 rc = SUPR0IdcComponentDeregisterFactory(&pGlobals->SupDrvIDC, &pGlobals->SupDrvFactory);
1337 AssertRC(rc);
1338 if (!vboxNetFltCanUnload(pGlobals))
1339 {
1340 rc = SUPR0IdcComponentRegisterFactory(&pGlobals->SupDrvIDC, &pGlobals->SupDrvFactory);
1341 AssertRC(rc);
1342 return VERR_WRONG_ORDER;
1343 }
1344
1345 SUPR0IdcClose(&pGlobals->SupDrvIDC);
1346 pGlobals->fIDCOpen = false;
1347 }
1348
1349 return rc;
1350}
1351
1352
1353/**
1354 * Establishes the IDC connection to SUPDRV and registers our component factory.
1355 *
1356 * @returns VBox status code.
1357 * @param pGlobals Pointer to the globals.
1358 * @sa vboxNetFltInitGlobalsAndIdc().
1359 */
1360DECLHIDDEN(int) vboxNetFltInitIdc(PVBOXNETFLTGLOBALS pGlobals)
1361{
1362 int rc;
1363 Assert(!pGlobals->fIDCOpen);
1364
1365 /*
1366 * Establish a connection to SUPDRV and register our component factory.
1367 */
1368 rc = SUPR0IdcOpen(&pGlobals->SupDrvIDC, 0 /* iReqVersion = default */, 0 /* iMinVersion = default */, NULL, NULL, NULL);
1369 if (RT_SUCCESS(rc))
1370 {
1371 rc = SUPR0IdcComponentRegisterFactory(&pGlobals->SupDrvIDC, &pGlobals->SupDrvFactory);
1372 if (RT_SUCCESS(rc))
1373 {
1374 pGlobals->fIDCOpen = true;
1375 Log(("VBoxNetFlt: pSession=%p\n", SUPR0IdcGetSession(&pGlobals->SupDrvIDC)));
1376 return rc;
1377 }
1378
1379 /* bail out. */
1380 LogRel(("VBoxNetFlt: Failed to register component factory, rc=%Rrc\n", rc));
1381 SUPR0IdcClose(&pGlobals->SupDrvIDC);
1382 }
1383
1384 return rc;
1385}
1386
1387
1388/**
1389 * Deletes the globals.
1390 *
1391 * This must be called after the IDC connection has been closed,
1392 * see vboxNetFltTryDeleteIdc().
1393 *
1394 * @param pGlobals Pointer to the globals.
1395 * @sa vboxNetFltTryDeleteIdcAndGlobals()
1396 */
1397DECLHIDDEN(void) vboxNetFltDeleteGlobals(PVBOXNETFLTGLOBALS pGlobals)
1398{
1399 Assert(!pGlobals->fIDCOpen);
1400
1401 /*
1402 * Release resources.
1403 */
1404 RTSemFastMutexDestroy(pGlobals->hFastMtx);
1405 pGlobals->hFastMtx = NIL_RTSEMFASTMUTEX;
1406}
1407
1408
1409/**
1410 * Initializes the globals.
1411 *
1412 * @returns VBox status code.
1413 * @param pGlobals Pointer to the globals.
1414 * @sa vboxNetFltInitGlobalsAndIdc().
1415 */
1416DECLHIDDEN(int) vboxNetFltInitGlobals(PVBOXNETFLTGLOBALS pGlobals)
1417{
1418 /*
1419 * Initialize the common portions of the structure.
1420 */
1421 int rc = RTSemFastMutexCreate(&pGlobals->hFastMtx);
1422 if (RT_SUCCESS(rc))
1423 {
1424 pGlobals->pInstanceHead = NULL;
1425
1426 pGlobals->TrunkFactory.pfnRelease = vboxNetFltFactoryRelease;
1427 pGlobals->TrunkFactory.pfnCreateAndConnect = vboxNetFltFactoryCreateAndConnect;
1428#if defined(RT_OS_WINDOWS) && defined(VBOXNETADP)
1429 memcpy(pGlobals->SupDrvFactory.szName, "VBoxNetAdp", sizeof("VBoxNetAdp"));
1430#else
1431 memcpy(pGlobals->SupDrvFactory.szName, "VBoxNetFlt", sizeof("VBoxNetFlt"));
1432#endif
1433 pGlobals->SupDrvFactory.pfnQueryFactoryInterface = vboxNetFltQueryFactoryInterface;
1434 pGlobals->fIDCOpen = false;
1435
1436 return rc;
1437 }
1438
1439 return rc;
1440}
1441
1442
1443/**
1444 * Called by the native part when the OS wants the driver to unload.
1445 *
1446 * @returns VINF_SUCCESS on success, VERR_WRONG_ORDER if we're busy.
1447 *
1448 * @param pGlobals Pointer to the globals.
1449 */
1450DECLHIDDEN(int) vboxNetFltTryDeleteIdcAndGlobals(PVBOXNETFLTGLOBALS pGlobals)
1451{
1452 int rc = vboxNetFltTryDeleteIdc(pGlobals);
1453 if (RT_SUCCESS(rc))
1454 vboxNetFltDeleteGlobals(pGlobals);
1455 return rc;
1456}
1457
1458
1459/**
1460 * Called by the native driver/kext module initialization routine.
1461 *
1462 * It will initialize the common parts of the globals, assuming the caller
1463 * has already taken care of the OS specific bits, and establish the IDC
1464 * connection to SUPDRV.
1465 *
1466 * @returns VBox status code.
1467 * @param pGlobals Pointer to the globals.
1468 */
1469DECLHIDDEN(int) vboxNetFltInitGlobalsAndIdc(PVBOXNETFLTGLOBALS pGlobals)
1470{
1471 /*
1472 * Initialize the common portions of the structure.
1473 */
1474 int rc = vboxNetFltInitGlobals(pGlobals);
1475 if (RT_SUCCESS(rc))
1476 {
1477 rc = vboxNetFltInitIdc(pGlobals);
1478 if (RT_SUCCESS(rc))
1479 return rc;
1480
1481 /* bail out. */
1482 vboxNetFltDeleteGlobals(pGlobals);
1483 }
1484
1485 return rc;
1486}
1487
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