VirtualBox

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

Last change on this file since 28587 was 28088, checked in by vboxsync, 15 years ago

vboxNetFltPortIsHostMac: Same as with IsPromiscuous.

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