VirtualBox

source: vbox/trunk/src/VBox/Devices/Network/DrvTAP.cpp@ 5126

Last change on this file since 5126 was 5126, checked in by vboxsync, 18 years ago

Solaris

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 34.7 KB
Line 
1/** $Id: */
2/** @file
3 * Universial TAP network transport driver.
4 */
5
6/*
7 * Copyright (C) 2006-2007 innotek GmbH
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 as published by the Free Software Foundation,
13 * in version 2 as it comes in the "COPYING" file of the VirtualBox OSE
14 * distribution. VirtualBox OSE is distributed in the hope that it will
15 * be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18#define ASYNC_NET
19
20/*******************************************************************************
21* Header Files *
22*******************************************************************************/
23#define LOG_GROUP LOG_GROUP_DRV_TUN
24#include <VBox/log.h>
25#include <VBox/pdmdrv.h>
26
27#include <iprt/assert.h>
28#include <iprt/file.h>
29#include <iprt/string.h>
30#include <iprt/path.h>
31#ifdef ASYNC_NET
32# include <iprt/thread.h>
33# include <iprt/asm.h>
34# include <iprt/semaphore.h>
35#endif
36
37#include <sys/ioctl.h>
38#include <sys/poll.h>
39#ifdef RT_OS_SOLARIS
40# include <sys/stat.h>
41# include <sys/ethernet.h>
42# include <sys/sockio.h>
43# include <netinet/in.h>
44# include <netinet/in_systm.h>
45# include <netinet/ip.h>
46# include <netinet/ip_icmp.h>
47# include <netinet/udp.h>
48# include <netinet/tcp.h>
49# include <net/if.h>
50# include <stropts.h>
51# include <fcntl.h>
52# include <ctype.h>
53# include <stdlib.h>
54#else
55# include <sys/fcntl.h>
56#endif
57#include <errno.h>
58#ifdef ASYNC_NET
59# include <unistd.h>
60#endif
61
62#ifdef RT_OS_L4
63# include <l4/vboxserver/file.h>
64#endif
65
66#include "Builtins.h"
67
68
69/*******************************************************************************
70* Structures and Typedefs *
71*******************************************************************************/
72typedef enum ASYNCSTATE
73{
74 //ASYNCSTATE_SUSPENDED = 1,
75 ASYNCSTATE_RUNNING,
76 ASYNCSTATE_TERMINATE
77} ASYNCSTATE;
78
79/**
80 * Block driver instance data.
81 */
82typedef struct DRVTAP
83{
84 /** The network interface. */
85 PDMINETWORKCONNECTOR INetworkConnector;
86 /** The network interface. */
87 PPDMINETWORKPORT pPort;
88 /** Pointer to the driver instance. */
89 PPDMDRVINS pDrvIns;
90 /** TAP device file handle. */
91 RTFILE FileDevice;
92 /** The configured TAP device name. */
93 char *pszDeviceName;
94#ifdef RT_OS_SOLARIS
95 /** The actual TAP device name. */
96 char *pszDeviceNameActual;
97#endif
98 /** TAP setup application. */
99 char *pszSetupApplication;
100 /** TAP terminate application. */
101 char *pszTerminateApplication;
102#ifdef ASYNC_NET
103 /** The write end of the control pipe. */
104 RTFILE PipeWrite;
105 /** The read end of the control pipe. */
106 RTFILE PipeRead;
107 /** The thread state. */
108 ASYNCSTATE volatile enmState;
109 /** Reader thread. */
110 RTTHREAD Thread;
111 /** We are waiting for more receive buffers. */
112 uint32_t volatile fOutOfSpace;
113 /** Event semaphore for blocking on receive. */
114 RTSEMEVENT EventOutOfSpace;
115#endif
116
117#ifdef VBOX_WITH_STATISTICS
118 /** Number of sent packets. */
119 STAMCOUNTER StatPktSent;
120 /** Number of sent bytes. */
121 STAMCOUNTER StatPktSentBytes;
122 /** Number of received packets. */
123 STAMCOUNTER StatPktRecv;
124 /** Number of received bytes. */
125 STAMCOUNTER StatPktRecvBytes;
126 /** Profiling packet transmit runs. */
127 STAMPROFILE StatTransmit;
128 /** Profiling packet receive runs. */
129 STAMPROFILEADV StatReceive;
130#ifdef ASYNC_NET
131 STAMPROFILE StatRecvOverflows;
132#endif
133#endif /* VBOX_WITH_STATISTICS */
134
135#ifdef LOG_ENABLED
136 /** The nano ts of the last transfer. */
137 uint64_t u64LastTransferTS;
138 /** The nano ts of the last receive. */
139 uint64_t u64LastReceiveTS;
140#endif
141} DRVTAP, *PDRVTAP;
142
143
144/** Converts a pointer to TAP::INetworkConnector to a PRDVTAP. */
145#define PDMINETWORKCONNECTOR_2_DRVTAP(pInterface) ( (PDRVTAP)((uintptr_t)pInterface - RT_OFFSETOF(DRVTAP, INetworkConnector)) )
146
147
148/*******************************************************************************
149* Internal Functions *
150*******************************************************************************/
151#ifdef RT_OS_SOLARIS
152static DECLCALLBACK(int) SolarisTAPAttach(PPDMDRVINS pDrvIns);
153#endif
154
155
156/**
157 * Send data to the network.
158 *
159 * @returns VBox status code.
160 * @param pInterface Pointer to the interface structure containing the called function pointer.
161 * @param pvBuf Data to send.
162 * @param cb Number of bytes to send.
163 * @thread EMT
164 */
165static DECLCALLBACK(int) drvTAPSend(PPDMINETWORKCONNECTOR pInterface, const void *pvBuf, size_t cb)
166{
167 PDRVTAP pData = PDMINETWORKCONNECTOR_2_DRVTAP(pInterface);
168 STAM_COUNTER_INC(&pData->StatPktSent);
169 STAM_COUNTER_ADD(&pData->StatPktSentBytes, cb);
170 STAM_PROFILE_START(&pData->StatTransmit, a);
171
172#ifdef LOG_ENABLED
173 uint64_t u64Now = RTTimeProgramNanoTS();
174 LogFlow(("drvTAPSend: %-4d bytes at %llu ns deltas: r=%llu t=%llu\n",
175 cb, u64Now, u64Now - pData->u64LastReceiveTS, u64Now - pData->u64LastTransferTS));
176 pData->u64LastTransferTS = u64Now;
177#endif
178 Log2(("drvTAPSend: pvBuf=%p cb=%#x\n"
179 "%.*Vhxd\n",
180 pvBuf, cb, cb, pvBuf));
181
182 int rc = RTFileWrite(pData->FileDevice, pvBuf, cb, NULL);
183
184 STAM_PROFILE_STOP(&pData->StatTransmit, a);
185 AssertRC(rc);
186 return rc;
187}
188
189
190/**
191 * Set promiscuous mode.
192 *
193 * This is called when the promiscuous mode is set. This means that there doesn't have
194 * to be a mode change when it's called.
195 *
196 * @param pInterface Pointer to the interface structure containing the called function pointer.
197 * @param fPromiscuous Set if the adaptor is now in promiscuous mode. Clear if it is not.
198 * @thread EMT
199 */
200static DECLCALLBACK(void) drvTAPSetPromiscuousMode(PPDMINETWORKCONNECTOR pInterface, bool fPromiscuous)
201{
202 LogFlow(("drvTAPSetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
203 /* nothing to do */
204}
205
206
207/**
208 * Notification on link status changes.
209 *
210 * @param pInterface Pointer to the interface structure containing the called function pointer.
211 * @param enmLinkState The new link state.
212 * @thread EMT
213 */
214static DECLCALLBACK(void) drvTAPNotifyLinkChanged(PPDMINETWORKCONNECTOR pInterface, PDMNETWORKLINKSTATE enmLinkState)
215{
216 LogFlow(("drvNATNotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
217 /** @todo take action on link down and up. Stop the polling and such like. */
218}
219
220
221/**
222 * More receive buffer has become available.
223 *
224 * This is called when the NIC frees up receive buffers.
225 *
226 * @param pInterface Pointer to the interface structure containing the called function pointer.
227 * @thread EMT
228 */
229static DECLCALLBACK(void) drvTAPNotifyCanReceive(PPDMINETWORKCONNECTOR pInterface)
230{
231 PDRVTAP pData = PDMINETWORKCONNECTOR_2_DRVTAP(pInterface);
232
233 LogFlow(("drvTAPNotifyCanReceive:\n"));
234 /** @todo r=bird: With a bit unfavorable scheduling it's possible to get here
235 * before fOutOfSpace is set by the overflow code. This will mean that, unless
236 * more receive descriptors become available, the receive thread will be stuck
237 * until it times out and cause a hickup in the network traffic.
238 * There is a simple, but not perfect, workaround for this problem in DrvTAPOs2.cpp.
239 *
240 * A better solution would be to ditch the NotifyCanReceive callback and instead
241 * change the CanReceive to do all the work. This will reduce the amount of code
242 * duplication, and would permit pcnet to avoid queuing unnecessary ring-3 tasks.
243 */
244
245 /* ensure we wake up only once */
246 if (ASMAtomicXchgU32(&pData->fOutOfSpace, false))
247 RTSemEventSignal(pData->EventOutOfSpace);
248}
249
250
251#ifdef ASYNC_NET
252/**
253 * Asynchronous I/O thread for handling receive.
254 *
255 * @returns VINF_SUCCESS (ignored).
256 * @param Thread Thread handle.
257 * @param pvUser Pointer to a DRVTAP structure.
258 */
259static DECLCALLBACK(int) drvTAPAsyncIoThread(RTTHREAD ThreadSelf, void *pvUser)
260{
261 PDRVTAP pData = (PDRVTAP)pvUser;
262 LogFlow(("drvTAPAsyncIoThread: pData=%p\n", pData));
263 STAM_PROFILE_ADV_START(&pData->StatReceive, a);
264
265 int rc = RTSemEventCreate(&pData->EventOutOfSpace);
266 AssertRC(rc);
267
268 /*
269 * Polling loop.
270 */
271 for (;;)
272 {
273 /*
274 * Wait for something to become available.
275 */
276 struct pollfd aFDs[2];
277 aFDs[0].fd = pData->FileDevice;
278 aFDs[0].events = POLLIN | POLLPRI;
279 aFDs[0].revents = 0;
280 aFDs[1].fd = pData->PipeRead;
281 aFDs[1].events = POLLIN | POLLPRI | POLLERR | POLLHUP;
282 aFDs[1].revents = 0;
283 STAM_PROFILE_ADV_STOP(&pData->StatReceive, a);
284 errno=0;
285 rc = poll(&aFDs[0], ELEMENTS(aFDs), -1 /* infinite */);
286 STAM_PROFILE_ADV_START(&pData->StatReceive, a);
287 if ( rc > 0
288 && (aFDs[0].revents & (POLLIN | POLLPRI))
289 && !aFDs[1].revents)
290 {
291 /*
292 * Read the frame.
293 */
294 char achBuf[4096];
295 size_t cbRead = 0;
296 rc = RTFileRead(pData->FileDevice, achBuf, sizeof(achBuf), &cbRead);
297 if (VBOX_SUCCESS(rc))
298 {
299 AssertMsg(cbRead <= 1536, ("cbRead=%d\n", cbRead));
300
301 /*
302 * Wait for the device to have space for this frame.
303 */
304 size_t cbMax = pData->pPort->pfnCanReceive(pData->pPort);
305 if (cbMax < cbRead)
306 {
307 /** @todo receive overflow handling needs serious improving! */
308 STAM_PROFILE_ADV_STOP(&pData->StatReceive, a);
309 STAM_PROFILE_START(&pData->StatRecvOverflows, b);
310 while ( cbMax < cbRead
311 && pData->enmState != ASYNCSTATE_TERMINATE)
312 {
313 LogFlow(("drvTAPAsyncIoThread: cbMax=%d cbRead=%d waiting...\n", cbMax, cbRead));
314#if 1
315 /* We get signalled by the network driver. 50ms is just for sanity */
316 ASMAtomicXchgU32(&pData->fOutOfSpace, true);
317 RTSemEventWait(pData->EventOutOfSpace, 50);
318#else
319 RTThreadSleep(1);
320#endif
321 cbMax = pData->pPort->pfnCanReceive(pData->pPort);
322 }
323 ASMAtomicXchgU32(&pData->fOutOfSpace, false);
324 STAM_PROFILE_STOP(&pData->StatRecvOverflows, b);
325 STAM_PROFILE_ADV_START(&pData->StatReceive, a);
326 if (pData->enmState == ASYNCSTATE_TERMINATE)
327 break;
328 }
329
330 /*
331 * Pass the data up.
332 */
333#ifdef LOG_ENABLED
334 uint64_t u64Now = RTTimeProgramNanoTS();
335 LogFlow(("drvTAPAsyncIoThread: %-4d bytes at %llu ns deltas: r=%llu t=%llu\n",
336 cbRead, u64Now, u64Now - pData->u64LastReceiveTS, u64Now - pData->u64LastTransferTS));
337 pData->u64LastReceiveTS = u64Now;
338#endif
339 Log2(("drvTAPAsyncIoThread: cbRead=%#x\n"
340 "%.*Vhxd\n",
341 cbRead, cbRead, achBuf));
342 STAM_COUNTER_INC(&pData->StatPktRecv);
343 STAM_COUNTER_ADD(&pData->StatPktRecvBytes, cbRead);
344 rc = pData->pPort->pfnReceive(pData->pPort, achBuf, cbRead);
345 AssertRC(rc);
346 }
347 else
348 {
349 LogFlow(("drvTAPAsyncIoThread: RTFileRead -> %Vrc\n", rc));
350 if (rc == VERR_INVALID_HANDLE)
351 break;
352 RTThreadYield();
353 }
354 }
355 else if ( rc > 0
356 && aFDs[1].revents)
357 {
358 LogFlow(("drvTAPAsyncIoThread: Control message: enmState=%d revents=%#x\n", pData->enmState, aFDs[1].revents));
359 if (pData->enmState == ASYNCSTATE_TERMINATE)
360 break;
361 if (aFDs[1].revents & (POLLHUP | POLLERR | POLLNVAL))
362 break;
363
364 /* drain the pipe */
365 char ch;
366 size_t cbRead;
367 RTFileRead(pData->PipeRead, &ch, 1, &cbRead);
368 }
369 else
370 {
371 /*
372 * poll() failed for some reason. Yield to avoid eating too much CPU.
373 *
374 * EINTR errors have been seen frequently. They should be harmless, even
375 * if they are not supposed to occur in our setup.
376 */
377 if (errno == EINTR)
378 Log(("rc=%d revents=%#x,%#x errno=%p %s\n", rc, aFDs[0].revents, aFDs[1].revents, errno, strerror(errno)));
379 else
380 AssertMsgFailed(("rc=%d revents=%#x,%#x errno=%p %s\n", rc, aFDs[0].revents, aFDs[1].revents, errno, strerror(errno)));
381 RTThreadYield();
382 }
383 }
384
385 rc = RTSemEventDestroy(pData->EventOutOfSpace);
386 AssertRC(rc);
387
388 LogFlow(("drvTAPAsyncIoThread: returns %Vrc\n", VINF_SUCCESS));
389 STAM_PROFILE_ADV_STOP(&pData->StatReceive, a);
390 return VINF_SUCCESS;
391}
392
393#else
394/**
395 * Poller callback.
396 */
397static DECLCALLBACK(void) drvTAPPoller(PPDMDRVINS pDrvIns)
398{
399 /* check how much the device/driver can receive now. */
400 PDRVTAP pData = PDMINS2DATA(pDrvIns, PDRVTAP);
401 STAM_PROFILE_ADV_START(&pData->StatReceive, a);
402
403 size_t cbMax = pData->pPort->pfnCanReceive(pData->pPort);
404 while (cbMax > 0)
405 {
406 /* check for data to read */
407 struct pollfd aFDs[1];
408 aFDs[0].fd = pData->FileDevice;
409 aFDs[0].events = POLLIN | POLLPRI;
410 aFDs[0].revents = 0;
411 if (poll(&aFDs[0], 1, 0) > 0)
412 {
413 if (aFDs[0].revents & (POLLIN | POLLPRI))
414 {
415 /* data waiting, read it. */
416 char achBuf[4096];
417 size_t cbRead = 0;
418 int rc = RTFileRead(pData->FileDevice, achBuf, RT_MIN(sizeof(achBuf), cbMax), &cbRead);
419 if (VBOX_SUCCESS(rc))
420 {
421 STAM_COUNTER_INC(&pData->StatPktRecv);
422 STAM_COUNTER_ADD(&pData->StatPktRecvBytes, cbRead);
423
424 /* push it up to guy over us. */
425 Log2(("drvTAPPoller: cbRead=%#x\n"
426 "%.*Vhxd\n",
427 cbRead, cbRead, achBuf));
428 rc = pData->pPort->pfnReceive(pData->pPort, achBuf, cbRead);
429 AssertRC(rc);
430 }
431 else
432 AssertRC(rc);
433 if (VBOX_FAILURE(rc) || !cbRead)
434 break;
435 }
436 else
437 break;
438 }
439 else
440 break;
441
442 cbMax = pData->pPort->pfnCanReceive(pData->pPort);
443 }
444
445 STAM_PROFILE_ADV_STOP(&pData->StatReceive, a);
446}
447#endif
448
449
450#if defined(RT_OS_SOLARIS)
451/**
452 * Calls OS-specific TAP setup application/script.
453 *
454 * @returns VBox error code.
455 * @param pData The instance data.
456 */
457static int drvTAPSetupApplication(PDRVTAP pData)
458{
459 char *pszArgs[3];
460 pszArgs[0] = pData->pszSetupApplication;
461 pszArgs[1] = pData->pszDeviceNameActual;
462 pszArgs[2] = NULL;
463
464/** @todo use RTProcCreate */
465
466 Log2(("Starting TAP setup application: %s %s\n", pData->pszSetupApplication, pData->pszDeviceNameActual));
467 pid_t pid = fork();
468 if (pid < 0)
469 {
470 /* Bad. fork() failed! */
471 LogRel(("TAP#%d: Failed to fork() process for running TAP setup application: %s\n", pDrvIns->iInstance,
472 pData->pszSetupApplication, strerror(errno)));
473 return VERR_HOSTIF_INIT_FAILED;
474 }
475 if (pid == 0)
476 {
477 /* Child process. */
478 execv(pszArgs[0], pszArgs);
479 _exit(1);
480 }
481
482 /* Parent process. */
483 int result;
484 while (waitpid(pid, &result, 0) < 0)
485 ;
486 if (!WIFEXITED(result) || WEXITSTATUS(result) != 0)
487 {
488 LogRel(("TAP#%d: Failed to run TAP setup application: %s\n", pDrvIns->iInstance, pData->pszSetupApplication));
489 return VERR_HOSTIF_INIT_FAILED;
490 }
491
492 return VINF_SUCCESS;
493}
494
495
496/**
497 * Calls OS-specific TAP terminate application/script.
498 *
499 * @returns VBox error code.
500 * @param pData The instance data.
501 */
502static int drvTAPTerminateApplication(PDRVTAP pData)
503{
504 char *pszArgs[3];
505 pszArgs[0] = pData->pszTerminateApplication;
506 pszArgs[1] = pData->pszDeviceNameActual;
507 pszArgs[2] = NULL;
508
509/** @todo use RTProcCreate */
510
511 Log2(("Starting TAP terminate application: %s %s\n", pData->pszTerminateApplication, pData->pszDeviceNameActual));
512 pid_t pid = fork();
513 if (pid < 0)
514 {
515 /* Bad. fork() failed! */
516 LogRel(("TAP#%d: Failed to fork() process for running TAP terminate application: %s\n", pDrvIns->iInstance,
517 pData->pszTerminateApplication, strerror(errno)));
518 return VERR_HOSTIF_TERM_FAILED;
519 }
520 if (pid == 0)
521 {
522 /* Child process. */
523 execv(pszArgs[0], pszArgs);
524 _exit(1);
525 }
526
527 /* Parent process. */
528 int result;
529 while (waitpid(pid, &result, 0) < 0)
530 ;
531 if (!WIFEXITED(result) || WEXITSTATUS(result) != 0)
532 {
533 LogRel(("TAP#%d: Failed to run TAP terminate application: %s\n", pDrvIns->iInstance, pData->pszSetupApplication));
534 return VERR_HOSTIF_TERM_FAILED;
535 }
536
537 return VINF_SUCCESS;
538}
539
540#endif /* RT_OS_SOLARIS */
541
542
543#ifdef RT_OS_SOLARIS
544/** From net/if_tun.h, installed by Universal TUN/TAP driver */
545# define TUNNEWPPA (('T'<<16) | 0x0001)
546/** Whether to enable ARP for TAP. */
547# define VBOX_SOLARIS_TAP_ARP 1
548
549/**
550 * Creates/Attaches TAP device to IP.
551 *
552 * @returns VBox error code.
553 * @param pDrvIns The driver instance data.
554 * @param pszDevName Pointer to device name.
555 */
556static DECLCALLBACK(int) SolarisTAPAttach(PPDMDRVINS pDrvIns)
557{
558 PDRVTAP pData = PDMINS2DATA(pDrvIns, PDRVTAP);
559 LogFlow(("SolarisTapAttach: pData=%p\n", pData));
560
561
562 /* Close previously opened file desc., if any. */
563 static int s_IPFileDes = -1; /** @todo r=bird: what's the point of keeping this open? */
564 if (s_IPFileDes >= 0)
565 close(s_IPFileDes);
566
567 s_IPFileDes = open("/dev/udp", O_RDWR, 0);
568 if (s_IPFileDes < 0)
569 return PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
570 N_("Failed to open /dev/udp. errno=%d"), errno);
571
572 int TapFileDes = open("/dev/tap", O_RDWR, 0);
573 if (TapFileDes < 0)
574 return PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
575 N_("Failed to open /dev/tap for TAP. errno=%d"), errno);
576
577 /* Use the PPA from the ifname if possible (e.g "tap2", then use 2 as PPA) */
578 int iPPA = -1;
579 if (pData->pszDeviceName)
580 {
581 size_t cch = strlen(pData->pszDeviceName);
582 if (cch > 1 && isdigit(pData->pszDeviceName[cch - 1]) != 0)
583 iPPA = pData->pszDeviceName[cch - 1] - '0';
584 }
585
586 struct strioctl ioIF;
587 ioIF.ic_cmd = TUNNEWPPA;
588 ioIF.ic_len = sizeof(iPPA);
589 ioIF.ic_dp = (char *)(&iPPA);
590 ioIF.ic_timout = 0;
591 iPPA = ioctl(TapFileDes, I_STR, &ioIF);
592 if (iPPA < 0) /** @todo r=bird: leaving at least one file descriptor open. */
593 return PDMDrvHlpVMSetError(pDrvIns, VERR_HOSTIF_IOCTL, RT_SRC_POS,
594 N_("Failed to get new interface. errno=%d"), errno);
595
596 int InterfaceFD = open("/dev/tap", O_RDWR, 0);
597 if (!InterfaceFD)
598 return PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
599 N_("Failed to open interface /dev/tap. errno=%d"), errno);
600
601 if (ioctl(InterfaceFD, I_PUSH, "ip") == -1)
602 {
603 close(InterfaceFD);
604 return PDMDrvHlpVMSetError(pDrvIns, VERR_HOSTIF_IOCTL, RT_SRC_POS,
605 N_("Failed to push IP. errno=%d"), errno);
606 }
607
608 struct lifreq ifReq;
609 memset(&ifReq, 0, sizeof(ifReq));
610 if (ioctl(InterfaceFD, SIOCGLIFFLAGS, &ifReq) == -1)
611 LogRel(("TAP#%d: Failed to get interface flags.\n", pDrvIns->iInstance));
612
613 char szTmp[16];
614 char *pszDevName = pData->pszDeviceName;
615 if (!pData->pszDeviceName || !*pData->pszDeviceName)
616 {
617 RTStrPrintf(szTmp, sizeof(szTmp), "tap%d", iPPA);
618 pszDevName = szTmp;
619 }
620
621 ifReq.lifr_ppa = iPPA;
622 RTStrPrintf (ifReq.lifr_name, sizeof(ifReq.lifr_name), pszDevName);
623
624 if (ioctl(InterfaceFD, SIOCSLIFNAME, &ifReq) == -1)
625 LogRel(("TAP#%d: Failed to set PPA. errno=%d\n", pDrvIns->iInstance, errno));
626
627 if (ioctl(InterfaceFD, SIOCGLIFFLAGS, &ifReq) == -1)
628 LogRel(("TAP#%d: Failed to get interface flags after setting PPA. errno=%d\n", pDrvIns->iInstance, errno));
629
630#ifdef VBOX_SOLARIS_TAP_ARP
631 /* Interface */
632 if (ioctl(InterfaceFD, I_PUSH, "arp") == -1)
633 LogRel(("TAP#%d: Failed to push ARP to Interface FD. errno=%d\n", pDrvIns->iInstance, errno));
634
635 /* IP */
636 if (ioctl(s_IPFileDes, I_POP, NULL) == -1)
637 LogRel(("TAP#%d: Failed I_POP from IP FD. errno=%d\n", pDrvIns->iInstance, errno));
638
639 if (ioctl(s_IPFileDes, I_PUSH, "arp") == -1)
640 LogRel(("TAP#%d: Failed to push ARP to IP FD. errno=%d\n", pDrvIns->iInstance, errno));
641
642 /* ARP */
643 int ARPFileDes = open("/dev/tap", O_RDWR, 0);
644 if (ARPFileDes < 0)
645 LogRel(("TAP#%d: Failed to open for /dev/tap for ARP. errno=%d", pDrvIns->iInstance, errno));
646
647 if (ioctl(ARPFileDes, I_PUSH, "arp") == -1)
648 LogRel(("TAP#%d: Failed to push ARP to ARP FD. errno=%d\n", pDrvIns->iInstance, errno));
649
650 ioIF.ic_cmd = SIOCSLIFNAME;
651 ioIF.ic_timout = 0;
652 ioIF.ic_len = sizeof(ifReq);
653 ioIF.ic_dp = (char *)&ifReq;
654 if (ioctl(ARPFileDes, I_STR, &ioIF) == -1)
655 LogRel(("TAP#%d: Failed to set interface name to ARP.\n", pDrvIns->iInstance));
656#endif
657
658 /* We must use I_LINK and not I_PLINK as I_PLINK makes the link persistent.
659 * Then we would not be able unlink the interface if we reuse it.
660 * Even 'unplumb' won't work after that.
661 */
662 int IPMuxID = ioctl(s_IPFileDes, I_LINK, InterfaceFD);
663 if (IPMuxID == -1)
664 {
665 close(InterfaceFD);
666#ifdef VBOX_SOLARIS_TAP_ARP
667 close(ARPFileDes);
668#endif
669 LogRel(("TAP#%d: Cannot link TAP device to IP.\n", pDrvIns->iInstance));
670 return PDMDrvHlpVMSetError(pDrvIns, VERR_HOSTIF_IOCTL, RT_SRC_POS,
671 N_("Failed to link TAP device to IP. Check TAP interface name. errno=%d"), errno);
672 }
673
674#ifdef VBOX_SOLARIS_TAP_ARP
675 int ARPMuxID = ioctl(s_IPFileDes, I_LINK, ARPFileDes);
676 if (ARPMuxID == -1)
677 LogRel(("TAP#%d: Failed to link TAP device to ARP\n", pDrvIns->iInstance));
678
679 close(ARPFileDes);
680#endif
681 close(InterfaceFD);
682
683 /* Reuse ifReq */
684 memset(&ifReq, 0, sizeof(ifReq));
685 RTStrPrintf (ifReq.lifr_name, sizeof(ifReq.lifr_name), pszDevName);
686 ifReq.lifr_ip_muxid = IPMuxID;
687#ifdef VBOX_SOLARIS_TAP_ARP
688 ifReq.lifr_arp_muxid = ARPMuxID;
689#endif
690
691 if (ioctl(s_IPFileDes, SIOCSLIFMUXID, &ifReq) == -1)
692 {
693#ifdef VBOX_SOLARIS_TAP_ARP
694 ioctl(IPFileDes, I_PUNLINK, ARPMuxID);
695#endif
696 ioctl(IPFileDes, I_PUNLINK, IPMuxID);
697 close(s_IPFileDes);
698 s_IPFileDes = -1;
699 LogRel(("TAP#%d: Failed to set Mux ID.\n", pDrvIns->iInstance));
700 return PDMDrvHlpVMSetError(pDrvIns, VERR_HOSTIF_IOCTL, RT_SRC_POS,
701 N_("Failed to set Mux ID. Check TAP interface name. errno=%d"), errno);
702 }
703
704 /* what's the point? */
705 pData->FileDevice = (RTFILE)TapFileDes;
706 pData->pszDeviceNameActual = RTStrDup(pszDevName);
707
708 return VINF_SUCCESS;
709}
710
711#endif /* RT_OS_SOLARIS */
712
713
714/**
715 * Queries an interface to the driver.
716 *
717 * @returns Pointer to interface.
718 * @returns NULL if the interface was not supported by the driver.
719 * @param pInterface Pointer to this interface structure.
720 * @param enmInterface The requested interface identification.
721 * @thread Any thread.
722 */
723static DECLCALLBACK(void *) drvTAPQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
724{
725 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
726 PDRVTAP pData = PDMINS2DATA(pDrvIns, PDRVTAP);
727 switch (enmInterface)
728 {
729 case PDMINTERFACE_BASE:
730 return &pDrvIns->IBase;
731 case PDMINTERFACE_NETWORK_CONNECTOR:
732 return &pData->INetworkConnector;
733 default:
734 return NULL;
735 }
736}
737
738
739/**
740 * Destruct a driver instance.
741 *
742 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
743 * resources can be freed correctly.
744 *
745 * @param pDrvIns The driver instance data.
746 */
747static DECLCALLBACK(void) drvTAPDestruct(PPDMDRVINS pDrvIns)
748{
749 LogFlow(("drvTAPDestruct\n"));
750 PDRVTAP pData = PDMINS2DATA(pDrvIns, PDRVTAP);
751
752#ifdef ASYNC_NET
753 /*
754 * Terminate the Async I/O Thread.
755 */
756 ASMAtomicXchgSize(&pData->enmState, ASYNCSTATE_TERMINATE);
757 if (pData->Thread != NIL_RTTHREAD)
758 {
759 /* Ensure that it does not spin in the CanReceive loop */
760 if (ASMAtomicXchgU32(&pData->fOutOfSpace, false))
761 RTSemEventSignal(pData->EventOutOfSpace);
762
763 int rc = RTFileWrite(pData->PipeWrite, "", 1, NULL);
764 AssertRC(rc);
765 rc = RTThreadWait(pData->Thread, 5000, NULL);
766 AssertRC(rc);
767 pData->Thread = NIL_RTTHREAD;
768 }
769
770 /*
771 * Terminate the control pipe.
772 */
773 if (pData->PipeWrite != NIL_RTFILE)
774 {
775 int rc = RTFileClose(pData->PipeWrite);
776 AssertRC(rc);
777 pData->PipeWrite = NIL_RTFILE;
778 }
779 if (pData->PipeRead != NIL_RTFILE)
780 {
781 int rc = RTFileClose(pData->PipeRead);
782 AssertRC(rc);
783 pData->PipeRead = NIL_RTFILE;
784 }
785#endif
786
787#ifdef RT_OS_SOLARIS
788 if (pData->pszTerminateApplication)
789 drvTAPTerminateApplication(pData);
790
791 RTStrFree(pData->pszDeviceNameActual);
792#endif
793 MMR3HeapFree(pData->pszDeviceName);
794 MMR3HeapFree(pData->pszSetupApplication);
795 MMR3HeapFree(pData->pszTerminateApplication);
796}
797
798
799/**
800 * Construct a TAP network transport driver instance.
801 *
802 * @returns VBox status.
803 * @param pDrvIns The driver instance data.
804 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
805 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
806 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
807 * iInstance it's expected to be used a bit in this function.
808 */
809static DECLCALLBACK(int) drvTAPConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
810{
811 PDRVTAP pData = PDMINS2DATA(pDrvIns, PDRVTAP);
812
813 /*
814 * Init the static parts.
815 */
816 pData->pDrvIns = pDrvIns;
817 pData->FileDevice = NIL_RTFILE;
818 pData->pszDeviceName = NULL;
819#ifdef RT_OS_SOLARIS
820 pData->pszDeviceNameActual = NULL;
821#endif
822 pData->pszSetupApplication = NULL;
823 pData->pszTerminateApplication = NULL;
824#ifdef ASYNC_NET
825 pData->Thread = NIL_RTTHREAD;
826 pData->enmState = ASYNCSTATE_RUNNING;
827#endif
828 /* IBase */
829 pDrvIns->IBase.pfnQueryInterface = drvTAPQueryInterface;
830 /* INetwork */
831 pData->INetworkConnector.pfnSend = drvTAPSend;
832 pData->INetworkConnector.pfnSetPromiscuousMode = drvTAPSetPromiscuousMode;
833 pData->INetworkConnector.pfnNotifyLinkChanged = drvTAPNotifyLinkChanged;
834 pData->INetworkConnector.pfnNotifyCanReceive = drvTAPNotifyCanReceive;
835
836 /*
837 * Validate the config.
838 */
839 if (!CFGMR3AreValuesValid(pCfgHandle, "Device\0InitProg\0TermProg\0FileHandle\0TAPSetupApplication\0TAPTerminateApplication"))
840 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, "");
841
842 /*
843 * Check that no-one is attached to us.
844 */
845 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, NULL);
846 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
847 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_NO_ATTACH,
848 N_("Configuration error: Cannot attach drivers to the TAP driver!"));
849
850 /*
851 * Query the network port interface.
852 */
853 pData->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
854 if (!pData->pPort)
855 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
856 N_("Configuration error: The above device/driver didn't export the network port interface!"));
857
858 /*
859 * Read the configuration.
860 */
861#if defined(RT_OS_SOLARIS) /** @todo Other platforms' TAP code should be moved here from ConsoleImpl & VBoxBFE. */
862 rc = CFGMR3QueryStringAlloc(pCfgHandle, "TAPSetupApplication", &pData->pszSetupApplication);
863 if (VBOX_SUCCESS(rc))
864 {
865 if (!RTPathExists(pData->pszSetupApplication))
866 return PDMDrvHlpVMSetError(pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
867 N_("Invalid TAP setup program path: %s"), pData->pszSetupApplication);
868 }
869 else if (rc != VERR_CFGM_VALUE_NOT_FOUND)
870 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Configuration error: failed to query \"TAPTerminateApplication\""));
871
872 rc = CFGMR3QueryStringAlloc(pCfgHandle, "TAPTerminateApplication", &pData->pszTerminateApplication);
873 if (VBOX_SUCCESS(rc))
874 {
875 if (!RTPathExists(pData->pszTerminateApplication))
876 return PDMDrvHlpVMSetError(pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
877 N_("Invalid TAP terminate program path: %s"), pData->pszTerminateApplication);
878 }
879 else if (rc != VERR_CFGM_VALUE_NOT_FOUND)
880 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Configuration error: failed to query \"TAPTerminateApplication\""));
881
882
883 rc = CFGMR3QueryStringAlloc(pCfgHandle, "Device", &pData->pszDeviceName);
884 if (VBOX_FAILURE(rc))
885 return PDMDRV_SET_ERROR(pDrvIns, rc,
886 N_("Configuration error: Query for \"Device\" string failed!"));
887
888 /*
889 * Do the setup.
890 */
891 rc = SolarisTAPAttach(pDrvIns);
892 if (VBOX_FAILURE(rc))
893 return rc;
894
895 if (pData->pszSetupApplication)
896 {
897 rc = drvTAPSetupApplication(pData);
898 if (RT_SUCCESS(rc))
899 return rc;
900 }
901
902#else /* !SOLARIS */
903
904 int32_t iFile;
905 rc = CFGMR3QueryS32(pCfgHandle, "FileHandle", &iFile);
906 if (VBOX_FAILURE(rc))
907 return PDMDRV_SET_ERROR(pDrvIns, rc,
908 N_("Configuration error: Query for \"FileHandle\" 32-bit signed integer failed!"));
909 pData->FileDevice = (RTFILE)iFile;
910 if (!RTFileIsValid(pData->FileDevice))
911 return PDMDrvHlpVMSetError(pDrvIns, VERR_INVALID_HANDLE, RT_SRC_POS,
912 N_("The TAP file handle %RTfile is not valid!"), pData->FileDevice);
913#endif /* !SOLARIS */
914
915 /*
916 * Make sure the descriptor is non-blocking and valid.
917 *
918 * We should actually query if it's a TAP device, but I haven't
919 * found any way to do that.
920 */
921 if (fcntl(pData->FileDevice, F_SETFL, O_NONBLOCK) == -1)
922 return PDMDrvHlpVMSetError(pDrvIns, VERR_HOSTIF_IOCTL, RT_SRC_POS,
923 N_("Configuration error: Failed to configure /dev/net/tun. errno=%d"), errno);
924 /** @todo determine device name. This can be done by reading the link /proc/<pid>/fd/<fd> */
925 Log(("drvTAPContruct: %d (from fd)\n", pData->FileDevice));
926 rc = VINF_SUCCESS;
927
928#ifdef ASYNC_NET
929 /*
930 * Create the control pipe.
931 */
932 int fds[2];
933#ifdef RT_OS_L4
934 /* XXX We need to tell the library which interface we are using */
935 fds[0] = vboxrtLinuxFd2VBoxFd(VBOXRT_FT_TAP, 0);
936#endif
937 if (pipe(&fds[0]) != 0) /** @todo RTPipeCreate() or something... */
938 {
939 int rc = RTErrConvertFromErrno(errno);
940 AssertRC(rc);
941 return rc;
942 }
943 pData->PipeRead = fds[0];
944 pData->PipeWrite = fds[1];
945
946 /*
947 * Create the async I/O thread.
948 */
949 rc = RTThreadCreate(&pData->Thread, drvTAPAsyncIoThread, pData, 128*_1K, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "TAP");
950 AssertRCReturn(rc, rc);
951#else
952 /*
953 * Register poller
954 */
955 rc = pDrvIns->pDrvHlp->pfnPDMPollerRegister(pDrvIns, drvTAPPoller);
956 AssertRCReturn(rc, rc);
957#endif
958
959#ifdef VBOX_WITH_STATISTICS
960 /*
961 * Statistics.
962 */
963 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatPktSent, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of sent packets.", "/Drivers/TAP%d/Packets/Sent", pDrvIns->iInstance);
964 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatPktSentBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Number of sent bytes.", "/Drivers/TAP%d/Bytes/Sent", pDrvIns->iInstance);
965 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatPktRecv, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of received packets.", "/Drivers/TAP%d/Packets/Received", pDrvIns->iInstance);
966 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatPktRecvBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Number of received bytes.", "/Drivers/TAP%d/Bytes/Received", pDrvIns->iInstance);
967 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatTransmit, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling packet transmit runs.", "/Drivers/TAP%d/Transmit", pDrvIns->iInstance);
968 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatReceive, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling packet receive runs.", "/Drivers/TAP%d/Receive", pDrvIns->iInstance);
969# ifdef ASYNC_NET
970 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatRecvOverflows, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_OCCURENCE, "Profiling packet receive overflows.", "/Drivers/TAP%d/RecvOverflows", pDrvIns->iInstance);
971# endif
972#endif /* VBOX_WITH_STATISTICS */
973
974 return rc;
975}
976
977
978/**
979 * TAP network transport driver registration record.
980 */
981const PDMDRVREG g_DrvHostInterface =
982{
983 /* u32Version */
984 PDM_DRVREG_VERSION,
985 /* szDriverName */
986 "HostInterface",
987 /* pszDescription */
988 "TAP Network Transport Driver",
989 /* fFlags */
990 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
991 /* fClass. */
992 PDM_DRVREG_CLASS_NETWORK,
993 /* cMaxInstances */
994 ~0,
995 /* cbInstance */
996 sizeof(DRVTAP),
997 /* pfnConstruct */
998 drvTAPConstruct,
999 /* pfnDestruct */
1000 drvTAPDestruct,
1001 /* pfnIOCtl */
1002 NULL,
1003 /* pfnPowerOn */
1004 NULL,
1005 /* pfnReset */
1006 NULL,
1007 /* pfnSuspend */
1008 NULL, /** @todo Do power on, suspend and resume handlers! */
1009 /* pfnResume */
1010 NULL,
1011 /* pfnDetach */
1012 NULL,
1013 /* pfnPowerOff */
1014 NULL
1015};
1016
Note: See TracBrowser for help on using the repository browser.

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