VirtualBox

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

最後變更 在這個檔案從29278是 29150,由 vboxsync 提交於 15 年 前

net[flt|adp]/win: TrunkIf state fixes

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Id
檔案大小: 53.9 KB
 
1/* $Id: VBoxNetFlt.c 29150 2010-05-06 13:13:03Z 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.alldomusa.eu.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->fRediscoveryPending);
869 Assert(!pThis->cBusy);
870#ifdef VBOXNETFLT_STATIC_CONFIG
871 Assert(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Unconnected);
872 /* INTNETTRUNKIFSTATE_DISCONNECTING means "not connected" here
873 * we use the INTNETTRUNKIFSTATE_DISCONNECTING state for consistency of cases when trunk
874 * was never connected and was connected and disconnected.
875 * In the latter case we end up with INTNETTRUNKIFSTATE_DICONNECTING,
876 * so use the same state for the former */
877 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_DISCONNECTING);
878#else
879 Assert(vboxNetFltGetState(pThis) == kVBoxNetFltInsState_Initializing);
880 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_INACTIVE);
881#endif
882
883 /*
884 * Do the job.
885 * Note that we're calling the os stuff while owning the semaphore here.
886 */
887 pThis->pSwitchPort = pSwitchPort;
888 rc = vboxNetFltOsConnectIt(pThis);
889 if (RT_SUCCESS(rc))
890 {
891 vboxNetFltSetState(pThis, kVBoxNetFltInsState_Connected);
892 *ppIfPort = &pThis->MyPort;
893 }
894 else
895 pThis->pSwitchPort = NULL;
896
897#ifdef VBOXNETFLT_STATIC_CONFIG
898 /* INTNETTRUNKIFSTATE_DISCONNECTING means "not connected" here
899 * we use the INTNETTRUNKIFSTATE_DISCONNECTING state for consistency of cases when trunk
900 * was never connected and was connected and disconnected.
901 * In the latter case we end up with INTNETTRUNKIFSTATE_DISCONNECTING,
902 * so use the same state for the former */
903 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_DISCONNECTING);
904#else
905 Assert(pThis->enmTrunkState == INTNETTRUNKIFSTATE_INACTIVE);
906#endif
907 return rc;
908}
909
910
911/**
912 * Creates a new instance.
913 *
914 * The new instance will be in the suspended state in a dynamic config and in
915 * the inactive in a static one.
916 *
917 * Called without owning the lock, but will request is several times.
918 *
919 * @returns VBox status code.
920 * @param pGlobals The globals.
921 * @param pszName The instance name.
922 * @param pSwitchPort The port on the switch that we're connected with (dynamic only).
923 * @param fNoPromisc Do not attempt going into promiscuous mode.
924 * @param pvContext Context argument for vboxNetFltOsInitInstance.
925 * @param ppIfPort Where to store the pointer to our port interface (dynamic only).
926 */
927static int vboxNetFltNewInstance(PVBOXNETFLTGLOBALS pGlobals, const char *pszName, PINTNETTRUNKSWPORT pSwitchPort,
928 bool fNoPromisc, void *pvContext, PINTNETTRUNKIFPORT *ppIfPort)
929{
930 /*
931 * Allocate and initialize a new instance before requesting the mutex.
932 */
933 int rc;
934 size_t const cchName = strlen(pszName);
935 PVBOXNETFLTINS pNew = (PVBOXNETFLTINS)RTMemAllocZ(RT_OFFSETOF(VBOXNETFLTINS, szName[cchName + 1]));
936 if (!pNew)
937 return VERR_INTNET_FLT_IF_FAILED;
938 pNew->pNext = NULL;
939 pNew->MyPort.u32Version = INTNETTRUNKIFPORT_VERSION;
940 pNew->MyPort.pfnRetain = vboxNetFltPortRetain;
941 pNew->MyPort.pfnRelease = vboxNetFltPortRelease;
942 pNew->MyPort.pfnDisconnectAndRelease= vboxNetFltPortDisconnectAndRelease;
943 pNew->MyPort.pfnSetState = vboxNetFltPortSetState;
944 pNew->MyPort.pfnWaitForIdle = vboxNetFltPortWaitForIdle;
945 pNew->MyPort.pfnXmit = vboxNetFltPortXmit;
946 pNew->MyPort.u32VersionEnd = INTNETTRUNKIFPORT_VERSION;
947 pNew->pSwitchPort = pSwitchPort;
948 pNew->pGlobals = pGlobals;
949 pNew->hSpinlock = NIL_RTSPINLOCK;
950 pNew->enmState = kVBoxNetFltInsState_Initializing;
951#ifdef VBOXNETFLT_STATIC_CONFIG
952 /* for consistency of cases when trunk was never connected and was connected and disconnected.
953 * In the latter case we end up with INTNETTRUNKIFSTATE_DISCONNECTING,
954 * so use the same state for the former */
955 pNew->enmTrunkState = INTNETTRUNKIFSTATE_DISCONNECTING;
956#else
957 pNew->enmTrunkState = INTNETTRUNKIFSTATE_INACTIVE;
958#endif
959 pNew->fDisconnectedFromHost = false;
960 pNew->fRediscoveryPending = false;
961 pNew->fDisablePromiscuous = fNoPromisc;
962 pNew->NanoTSLastRediscovery = INT64_MAX;
963 pNew->cRefs = 1;
964 pNew->cBusy = 0;
965 pNew->hEventIdle = NIL_RTSEMEVENT;
966 memcpy(pNew->szName, pszName, cchName + 1);
967
968 rc = RTSpinlockCreate(&pNew->hSpinlock);
969 if (RT_SUCCESS(rc))
970 {
971 rc = RTSemEventCreate(&pNew->hEventIdle);
972 if (RT_SUCCESS(rc))
973 {
974 rc = vboxNetFltOsPreInitInstance(pNew);
975 if (RT_SUCCESS(rc))
976 {
977 /*
978 * Insert the instance into the chain, checking for
979 * duplicates first of course (race).
980 */
981 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
982 if (RT_SUCCESS(rc))
983 {
984 if (!vboxNetFltFindInstanceLocked(pGlobals, pszName))
985 {
986 pNew->pNext = pGlobals->pInstanceHead;
987 pGlobals->pInstanceHead = pNew;
988 RTSemFastMutexRelease(pGlobals->hFastMtx);
989
990 /*
991 * Call the OS specific initialization code.
992 */
993 rc = vboxNetFltOsInitInstance(pNew, pvContext);
994 RTSemFastMutexRequest(pGlobals->hFastMtx);
995 if (RT_SUCCESS(rc))
996 {
997#ifdef VBOXNETFLT_STATIC_CONFIG
998 /*
999 * Static instances are unconnected at birth.
1000 */
1001 Assert(!pSwitchPort);
1002 pNew->enmState = kVBoxNetFltInsState_Unconnected;
1003 RTSemFastMutexRelease(pGlobals->hFastMtx);
1004 *ppIfPort = &pNew->MyPort;
1005 return rc;
1006
1007#else /* !VBOXNETFLT_STATIC_CONFIG */
1008 /*
1009 * Connect it as well, the OS specific bits has to be done outside
1010 * the lock as they may call back to into intnet.
1011 */
1012 rc = vboxNetFltConnectIt(pNew, pSwitchPort, ppIfPort);
1013 if (RT_SUCCESS(rc))
1014 {
1015 RTSemFastMutexRelease(pGlobals->hFastMtx);
1016 Assert(*ppIfPort == &pNew->MyPort);
1017 return rc;
1018 }
1019
1020 /* Bail out (failed). */
1021 vboxNetFltOsDeleteInstance(pNew);
1022#endif /* !VBOXNETFLT_STATIC_CONFIG */
1023 }
1024 vboxNetFltUnlinkLocked(pGlobals, pNew);
1025 }
1026 else
1027 rc = VERR_INTNET_FLT_IF_BUSY;
1028 RTSemFastMutexRelease(pGlobals->hFastMtx);
1029 }
1030 }
1031 RTSemEventDestroy(pNew->hEventIdle);
1032 }
1033 RTSpinlockDestroy(pNew->hSpinlock);
1034 }
1035
1036 RTMemFree(pNew);
1037 return rc;
1038}
1039
1040
1041#ifdef VBOXNETFLT_STATIC_CONFIG
1042/**
1043 * Searches for the NetFlt instance by its name and creates the new one if not found.
1044 *
1045 * @returns VBox status code.
1046 * @retval VINF_SUCCESS and *ppInstance if a new instance was created.
1047 * @retval VINF_ALREADY_INITIALIZED and *ppInstance if an instance already exists.
1048 *
1049 * @param pGlobal Pointer to the globals.
1050 * @param pszName The instance name.
1051 * @param ppInstance Where to return the instance pointer on success.
1052 * @param pvContext Context which needs to be passed along to vboxNetFltOsInitInstance.
1053 */
1054DECLHIDDEN(int) vboxNetFltSearchCreateInstance(PVBOXNETFLTGLOBALS pGlobals, const char *pszName, PVBOXNETFLTINS *ppInstance, void *pvContext)
1055{
1056 PINTNETTRUNKIFPORT pIfPort;
1057 PVBOXNETFLTINS pCur;
1058 VBOXNETFTLINSSTATE enmState;
1059 int rc;
1060
1061 *ppInstance = NULL;
1062 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1063 AssertRCReturn(rc, rc);
1064
1065 /*
1066 * Look for an existing instance in the list.
1067 *
1068 * There might be an existing one in the list if the driver was unbound
1069 * while it was connected to an internal network. We're running into
1070 * a destruction race that is a bit similar to the one in
1071 * vboxNetFltFactoryCreateAndConnect, only the roles are reversed
1072 * and we're not in a position to back down. Instead of backing down
1073 * we'll delay a bit giving the other thread time to complete the
1074 * destructor.
1075 */
1076 pCur = vboxNetFltFindInstanceLocked(pGlobals, pszName);
1077 while (pCur)
1078 {
1079 uint32_t cRefs = ASMAtomicIncU32(&pCur->cRefs);
1080 if (cRefs > 1)
1081 {
1082 enmState = vboxNetFltGetState(pCur);
1083 switch (enmState)
1084 {
1085 case kVBoxNetFltInsState_Unconnected:
1086 case kVBoxNetFltInsState_Connected:
1087 case kVBoxNetFltInsState_Disconnecting:
1088 if (pCur->fDisconnectedFromHost)
1089 {
1090 /* Wait for it to exit the transitional disconnecting
1091 state. It might otherwise be running the risk of
1092 upsetting the OS specific code... */
1093 /** @todo This reconnect stuff should be serialized correctly for static
1094 * devices. Shouldn't it? In the dynamic case we're using the INTNET
1095 * outbound thrunk lock, but that doesn't quite cut it here, or does
1096 * it? We could either transition to initializing or make a callback
1097 * while owning the mutext here... */
1098 if (enmState == kVBoxNetFltInsState_Disconnecting)
1099 {
1100 do
1101 {
1102 RTSemFastMutexRelease(pGlobals->hFastMtx);
1103 RTThreadSleep(2); /* (2ms) */
1104 RTSemFastMutexRequest(pGlobals->hFastMtx);
1105 enmState = vboxNetFltGetState(pCur);
1106 }
1107 while (enmState == kVBoxNetFltInsState_Disconnecting);
1108 AssertMsg(enmState == kVBoxNetFltInsState_Unconnected, ("%d\n", enmState));
1109 Assert(pCur->fDisconnectedFromHost);
1110 }
1111
1112 RTSemFastMutexRelease(pGlobals->hFastMtx);
1113 *ppInstance = pCur;
1114 return VINF_ALREADY_INITIALIZED;
1115 }
1116 /* fall thru */
1117
1118 default:
1119 {
1120 bool fDfH = pCur->fDisconnectedFromHost;
1121 RTSemFastMutexRelease(pGlobals->hFastMtx);
1122 vboxNetFltRelease(pCur, false /* fBusy */);
1123 LogRel(("VBoxNetFlt: Huh? An instance of '%s' already exists! [pCur=%p cRefs=%d fDfH=%RTbool enmState=%d]\n",
1124 pszName, pCur, cRefs - 1, fDfH, enmState));
1125 *ppInstance = NULL;
1126 return VERR_INTNET_FLT_IF_BUSY;
1127 }
1128 }
1129 }
1130
1131 /* Zero references, it's being destroyed. Delay a bit so the destructor
1132 can finish its work and try again. (vboxNetFltNewInstance will fail
1133 with duplicate name if we don't.) */
1134# ifdef RT_STRICT
1135 Assert(cRefs == 1);
1136 enmState = vboxNetFltGetState(pCur);
1137 AssertMsg( enmState == kVBoxNetFltInsState_Unconnected
1138 || enmState == kVBoxNetFltInsState_Disconnecting
1139 || enmState == kVBoxNetFltInsState_Destroyed, ("%d\n", enmState));
1140# endif
1141 ASMAtomicDecU32(&pCur->cRefs);
1142 RTSemFastMutexRelease(pGlobals->hFastMtx);
1143 RTThreadSleep(2); /* (2ms) */
1144 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1145 AssertRCReturn(rc, rc);
1146
1147 /* try again */
1148 pCur = vboxNetFltFindInstanceLocked(pGlobals, pszName);
1149 }
1150
1151 RTSemFastMutexRelease(pGlobals->hFastMtx);
1152
1153 /*
1154 * Try create a new instance.
1155 * (fNoPromisc is overridden in the vboxNetFltFactoryCreateAndConnect path, so pass true here.)
1156 */
1157 rc = vboxNetFltNewInstance(pGlobals, pszName, NULL, true /* fNoPromisc */, pvContext, &pIfPort);
1158 if (RT_SUCCESS(rc))
1159 *ppInstance = IFPORT_2_VBOXNETFLTINS(pIfPort);
1160 else
1161 *ppInstance = NULL;
1162
1163 return rc;
1164}
1165#endif /* VBOXNETFLT_STATIC_CONFIG */
1166
1167
1168/**
1169 * @copydoc INTNETTRUNKFACTORY::pfnCreateAndConnect
1170 */
1171static DECLCALLBACK(int) vboxNetFltFactoryCreateAndConnect(PINTNETTRUNKFACTORY pIfFactory, const char *pszName,
1172 PINTNETTRUNKSWPORT pSwitchPort, uint32_t fFlags,
1173 PINTNETTRUNKIFPORT *ppIfPort)
1174{
1175 PVBOXNETFLTGLOBALS pGlobals = (PVBOXNETFLTGLOBALS)((uint8_t *)pIfFactory - RT_OFFSETOF(VBOXNETFLTGLOBALS, TrunkFactory));
1176 PVBOXNETFLTINS pCur;
1177 int rc;
1178
1179 LogFlow(("vboxNetFltFactoryCreateAndConnect: pszName=%p:{%s} fFlags=%#x\n", pszName, pszName, fFlags));
1180 Assert(pGlobals->cFactoryRefs > 0);
1181 AssertMsgReturn(!(fFlags & ~(INTNETTRUNKFACTORY_FLAG_NO_PROMISC)),
1182 ("%#x\n", fFlags), VERR_INVALID_PARAMETER);
1183
1184 /*
1185 * Static: Find instance, check if busy, connect if not.
1186 * Dynamic: Check for duplicate / busy interface instance.
1187 */
1188 rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1189 AssertRCReturn(rc, rc);
1190
1191//#if defined(VBOXNETADP) && defined(RT_OS_WINDOWS)
1192// /* temporary hack to pick up the first adapter */
1193// pCur = pGlobals->pInstanceHead; /** @todo Don't for get to remove this temporary hack... :-) */
1194//#else
1195 pCur = vboxNetFltFindInstanceLocked(pGlobals, pszName);
1196//#endif
1197 if (pCur)
1198 {
1199#ifdef VBOXNETFLT_STATIC_CONFIG
1200 /* Try grab a reference. If the count had already reached zero we're racing the
1201 destructor code and must back down. */
1202 uint32_t cRefs = ASMAtomicIncU32(&pCur->cRefs);
1203 if (cRefs > 1)
1204 {
1205 if (vboxNetFltGetState(pCur) == kVBoxNetFltInsState_Unconnected)
1206 {
1207 pCur->fDisablePromiscuous = !!(fFlags & INTNETTRUNKFACTORY_FLAG_NO_PROMISC);
1208 rc = vboxNetFltConnectIt(pCur, pSwitchPort, ppIfPort);
1209 if (RT_SUCCESS(rc))
1210 pCur = NULL; /* Don't release it, reference given to the caller. */
1211 }
1212 else
1213 rc = VERR_INTNET_FLT_IF_BUSY;
1214 }
1215 else
1216 {
1217 Assert(cRefs == 1);
1218 ASMAtomicDecU32(&pCur->cRefs);
1219 pCur = NULL; /* nothing to release */
1220 rc = VERR_INTNET_FLT_IF_NOT_FOUND;
1221 }
1222
1223 RTSemFastMutexRelease(pGlobals->hFastMtx);
1224 if (pCur)
1225 vboxNetFltRelease(pCur, false /* fBusy */);
1226#else
1227 rc = VERR_INTNET_FLT_IF_BUSY;
1228 RTSemFastMutexRelease(pGlobals->hFastMtx);
1229#endif
1230 LogFlow(("vboxNetFltFactoryCreateAndConnect: returns %Rrc\n", rc));
1231 return rc;
1232 }
1233
1234 RTSemFastMutexRelease(pGlobals->hFastMtx);
1235
1236#ifdef VBOXNETFLT_STATIC_CONFIG
1237 rc = VERR_INTNET_FLT_IF_NOT_FOUND;
1238#else
1239 /*
1240 * Dynamically create a new instance.
1241 */
1242 rc = vboxNetFltNewInstance(pGlobals,
1243 pszName,
1244 pSwitchPort,
1245 !!(fFlags & INTNETTRUNKFACTORY_FLAG_NO_PROMISC),
1246 NULL,
1247 ppIfPort);
1248#endif
1249 LogFlow(("vboxNetFltFactoryCreateAndConnect: returns %Rrc\n", rc));
1250 return rc;
1251}
1252
1253
1254/**
1255 * @copydoc INTNETTRUNKFACTORY::pfnRelease
1256 */
1257static DECLCALLBACK(void) vboxNetFltFactoryRelease(PINTNETTRUNKFACTORY pIfFactory)
1258{
1259 PVBOXNETFLTGLOBALS pGlobals = (PVBOXNETFLTGLOBALS)((uint8_t *)pIfFactory - RT_OFFSETOF(VBOXNETFLTGLOBALS, TrunkFactory));
1260
1261 int32_t cRefs = ASMAtomicDecS32(&pGlobals->cFactoryRefs);
1262 Assert(cRefs >= 0); NOREF(cRefs);
1263 LogFlow(("vboxNetFltFactoryRelease: cRefs=%d (new)\n", cRefs));
1264}
1265
1266
1267/**
1268 * Implements the SUPDRV component factor interface query method.
1269 *
1270 * @returns Pointer to an interface. NULL if not supported.
1271 *
1272 * @param pSupDrvFactory Pointer to the componet factory registration structure.
1273 * @param pSession The session - unused.
1274 * @param pszInterfaceUuid The factory interface id.
1275 */
1276static DECLCALLBACK(void *) vboxNetFltQueryFactoryInterface(PCSUPDRVFACTORY pSupDrvFactory, PSUPDRVSESSION pSession, const char *pszInterfaceUuid)
1277{
1278 PVBOXNETFLTGLOBALS pGlobals = (PVBOXNETFLTGLOBALS)((uint8_t *)pSupDrvFactory - RT_OFFSETOF(VBOXNETFLTGLOBALS, SupDrvFactory));
1279
1280 /*
1281 * Convert the UUID strings and compare them.
1282 */
1283 RTUUID UuidReq;
1284 int rc = RTUuidFromStr(&UuidReq, pszInterfaceUuid);
1285 if (RT_SUCCESS(rc))
1286 {
1287 if (!RTUuidCompareStr(&UuidReq, INTNETTRUNKFACTORY_UUID_STR))
1288 {
1289 ASMAtomicIncS32(&pGlobals->cFactoryRefs);
1290 return &pGlobals->TrunkFactory;
1291 }
1292#ifdef LOG_ENABLED
1293 /* log legacy queries */
1294 /* else if (!RTUuidCompareStr(&UuidReq, INTNETTRUNKFACTORY_V1_UUID_STR))
1295 Log(("VBoxNetFlt: V1 factory query\n"));
1296 */
1297 else
1298 Log(("VBoxNetFlt: unknown factory interface query (%s)\n", pszInterfaceUuid));
1299#endif
1300 }
1301 else
1302 Log(("VBoxNetFlt: rc=%Rrc, uuid=%s\n", rc, pszInterfaceUuid));
1303
1304 return NULL;
1305}
1306
1307
1308/**
1309 * Checks whether the VBoxNetFlt wossname can be unloaded.
1310 *
1311 * This will return false if someone is currently using the module.
1312 *
1313 * @returns true if it's relatively safe to unload it, otherwise false.
1314 * @param pGlobals Pointer to the globals.
1315 */
1316DECLHIDDEN(bool) vboxNetFltCanUnload(PVBOXNETFLTGLOBALS pGlobals)
1317{
1318 int rc = RTSemFastMutexRequest(pGlobals->hFastMtx);
1319 bool fRc = !pGlobals->pInstanceHead
1320 && pGlobals->cFactoryRefs <= 0;
1321 RTSemFastMutexRelease(pGlobals->hFastMtx);
1322 AssertRC(rc);
1323 return fRc;
1324}
1325
1326
1327/**
1328 * Try to close the IDC connection to SUPDRV if established.
1329 *
1330 * @returns VBox status code.
1331 * @retval VINF_SUCCESS on success.
1332 * @retval VERR_WRONG_ORDER if we're busy.
1333 *
1334 * @param pGlobals Pointer to the globals.
1335 *
1336 * @sa vboxNetFltTryDeleteIdcAndGlobals()
1337 */
1338DECLHIDDEN(int) vboxNetFltTryDeleteIdc(PVBOXNETFLTGLOBALS pGlobals)
1339{
1340 int rc;
1341
1342 Assert(pGlobals->hFastMtx != NIL_RTSEMFASTMUTEX);
1343
1344 /*
1345 * Check before trying to deregister the factory.
1346 */
1347 if (!vboxNetFltCanUnload(pGlobals))
1348 return VERR_WRONG_ORDER;
1349
1350 if (!pGlobals->fIDCOpen)
1351 rc = VINF_SUCCESS;
1352 else
1353 {
1354 /*
1355 * Disconnect from SUPDRV and check that nobody raced us,
1356 * reconnect if that should happen.
1357 */
1358 rc = SUPR0IdcComponentDeregisterFactory(&pGlobals->SupDrvIDC, &pGlobals->SupDrvFactory);
1359 AssertRC(rc);
1360 if (!vboxNetFltCanUnload(pGlobals))
1361 {
1362 rc = SUPR0IdcComponentRegisterFactory(&pGlobals->SupDrvIDC, &pGlobals->SupDrvFactory);
1363 AssertRC(rc);
1364 return VERR_WRONG_ORDER;
1365 }
1366
1367 SUPR0IdcClose(&pGlobals->SupDrvIDC);
1368 pGlobals->fIDCOpen = false;
1369 }
1370
1371 return rc;
1372}
1373
1374
1375/**
1376 * Establishes the IDC connection to SUPDRV and registers our component factory.
1377 *
1378 * @returns VBox status code.
1379 * @param pGlobals Pointer to the globals.
1380 * @sa vboxNetFltInitGlobalsAndIdc().
1381 */
1382DECLHIDDEN(int) vboxNetFltInitIdc(PVBOXNETFLTGLOBALS pGlobals)
1383{
1384 int rc;
1385 Assert(!pGlobals->fIDCOpen);
1386
1387 /*
1388 * Establish a connection to SUPDRV and register our component factory.
1389 */
1390 rc = SUPR0IdcOpen(&pGlobals->SupDrvIDC, 0 /* iReqVersion = default */, 0 /* iMinVersion = default */, NULL, NULL, NULL);
1391 if (RT_SUCCESS(rc))
1392 {
1393 rc = SUPR0IdcComponentRegisterFactory(&pGlobals->SupDrvIDC, &pGlobals->SupDrvFactory);
1394 if (RT_SUCCESS(rc))
1395 {
1396 pGlobals->fIDCOpen = true;
1397 Log(("VBoxNetFlt: pSession=%p\n", SUPR0IdcGetSession(&pGlobals->SupDrvIDC)));
1398 return rc;
1399 }
1400
1401 /* bail out. */
1402 LogRel(("VBoxNetFlt: Failed to register component factory, rc=%Rrc\n", rc));
1403 SUPR0IdcClose(&pGlobals->SupDrvIDC);
1404 }
1405
1406 return rc;
1407}
1408
1409
1410/**
1411 * Deletes the globals.
1412 *
1413 * This must be called after the IDC connection has been closed,
1414 * see vboxNetFltTryDeleteIdc().
1415 *
1416 * @param pGlobals Pointer to the globals.
1417 * @sa vboxNetFltTryDeleteIdcAndGlobals()
1418 */
1419DECLHIDDEN(void) vboxNetFltDeleteGlobals(PVBOXNETFLTGLOBALS pGlobals)
1420{
1421 Assert(!pGlobals->fIDCOpen);
1422
1423 /*
1424 * Release resources.
1425 */
1426 RTSemFastMutexDestroy(pGlobals->hFastMtx);
1427 pGlobals->hFastMtx = NIL_RTSEMFASTMUTEX;
1428}
1429
1430
1431/**
1432 * Initializes the globals.
1433 *
1434 * @returns VBox status code.
1435 * @param pGlobals Pointer to the globals.
1436 * @sa vboxNetFltInitGlobalsAndIdc().
1437 */
1438DECLHIDDEN(int) vboxNetFltInitGlobals(PVBOXNETFLTGLOBALS pGlobals)
1439{
1440 /*
1441 * Initialize the common portions of the structure.
1442 */
1443 int rc = RTSemFastMutexCreate(&pGlobals->hFastMtx);
1444 if (RT_SUCCESS(rc))
1445 {
1446 pGlobals->pInstanceHead = NULL;
1447
1448 pGlobals->TrunkFactory.pfnRelease = vboxNetFltFactoryRelease;
1449 pGlobals->TrunkFactory.pfnCreateAndConnect = vboxNetFltFactoryCreateAndConnect;
1450#if defined(RT_OS_WINDOWS) && defined(VBOXNETADP)
1451 memcpy(pGlobals->SupDrvFactory.szName, "VBoxNetAdp", sizeof("VBoxNetAdp"));
1452#else
1453 memcpy(pGlobals->SupDrvFactory.szName, "VBoxNetFlt", sizeof("VBoxNetFlt"));
1454#endif
1455 pGlobals->SupDrvFactory.pfnQueryFactoryInterface = vboxNetFltQueryFactoryInterface;
1456 pGlobals->fIDCOpen = false;
1457
1458 return rc;
1459 }
1460
1461 return rc;
1462}
1463
1464
1465/**
1466 * Called by the native part when the OS wants the driver to unload.
1467 *
1468 * @returns VINF_SUCCESS on success, VERR_WRONG_ORDER if we're busy.
1469 *
1470 * @param pGlobals Pointer to the globals.
1471 */
1472DECLHIDDEN(int) vboxNetFltTryDeleteIdcAndGlobals(PVBOXNETFLTGLOBALS pGlobals)
1473{
1474 int rc = vboxNetFltTryDeleteIdc(pGlobals);
1475 if (RT_SUCCESS(rc))
1476 vboxNetFltDeleteGlobals(pGlobals);
1477 return rc;
1478}
1479
1480
1481/**
1482 * Called by the native driver/kext module initialization routine.
1483 *
1484 * It will initialize the common parts of the globals, assuming the caller
1485 * has already taken care of the OS specific bits, and establish the IDC
1486 * connection to SUPDRV.
1487 *
1488 * @returns VBox status code.
1489 * @param pGlobals Pointer to the globals.
1490 */
1491DECLHIDDEN(int) vboxNetFltInitGlobalsAndIdc(PVBOXNETFLTGLOBALS pGlobals)
1492{
1493 /*
1494 * Initialize the common portions of the structure.
1495 */
1496 int rc = vboxNetFltInitGlobals(pGlobals);
1497 if (RT_SUCCESS(rc))
1498 {
1499 rc = vboxNetFltInitIdc(pGlobals);
1500 if (RT_SUCCESS(rc))
1501 return rc;
1502
1503 /* bail out. */
1504 vboxNetFltDeleteGlobals(pGlobals);
1505 }
1506
1507 return rc;
1508}
1509
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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