VirtualBox

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

Last change on this file since 7974 was 7831, checked in by vboxsync, 17 years ago

net: moved the wait/notify mechanism for receive buffers into the device

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 38.3 KB
Line 
1/** $Id: DrvTAP.cpp 7831 2008-04-09 12:31:12Z vboxsync $ */
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 (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
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22#define LOG_GROUP LOG_GROUP_DRV_TUN
23#include <VBox/log.h>
24#include <VBox/pdmdrv.h>
25
26#include <iprt/assert.h>
27#include <iprt/file.h>
28#include <iprt/string.h>
29#include <iprt/path.h>
30#include <iprt/thread.h>
31#include <iprt/asm.h>
32#include <iprt/semaphore.h>
33#ifdef RT_OS_SOLARIS
34# include <iprt/process.h>
35# include <iprt/env.h>
36# ifdef VBOX_WITH_CROSSBOW
37# include <iprt/mem.h>
38# endif
39#endif
40
41#include <sys/ioctl.h>
42#include <sys/poll.h>
43#ifdef RT_OS_SOLARIS
44# include <sys/stat.h>
45# include <sys/ethernet.h>
46# include <sys/sockio.h>
47# include <netinet/in.h>
48# include <netinet/in_systm.h>
49# include <netinet/ip.h>
50# include <netinet/ip_icmp.h>
51# include <netinet/udp.h>
52# include <netinet/tcp.h>
53# include <net/if.h>
54# include <stropts.h>
55# include <fcntl.h>
56# include <ctype.h>
57# include <stdlib.h>
58# include <stdio.h>
59# ifdef VBOX_WITH_CROSSBOW
60# include <libdlpi.h>
61# endif
62#else
63# include <sys/fcntl.h>
64#endif
65#include <errno.h>
66#include <unistd.h>
67
68#ifdef RT_OS_L4
69# include <l4/vboxserver/file.h>
70#endif
71
72#include "Builtins.h"
73
74
75/*******************************************************************************
76* Structures and Typedefs *
77*******************************************************************************/
78/**
79 * Block driver instance data.
80 */
81typedef struct DRVTAP
82{
83 /** The network interface. */
84 PDMINETWORKCONNECTOR INetworkConnector;
85 /** The network interface. */
86 PPDMINETWORKPORT pPort;
87 /** Pointer to the driver instance. */
88 PPDMDRVINS pDrvIns;
89 /** TAP device file handle. */
90 RTFILE FileDevice;
91 /** The configured TAP device name. */
92 char *pszDeviceName;
93#ifdef RT_OS_SOLARIS
94# ifdef VBOX_WITH_CROSSBOW
95 /** Crossbow: MAC address of the device. */
96 PDMMAC MacAddress;
97 /** Crossbow: Handle of the NIC. */
98 dlpi_handle_t pDeviceHandle;
99# else
100 /** IP device file handle (/dev/udp). */
101 RTFILE IPFileDevice;
102# endif
103 /** Whether device name is obtained from setup application. */
104 bool fStatic;
105#endif
106 /** TAP setup application. */
107 char *pszSetupApplication;
108 /** TAP terminate application. */
109 char *pszTerminateApplication;
110 /** The write end of the control pipe. */
111 RTFILE PipeWrite;
112 /** The read end of the control pipe. */
113 RTFILE PipeRead;
114 /** Reader thread. */
115 PPDMTHREAD pThread;
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#endif /* VBOX_WITH_STATISTICS */
131
132#ifdef LOG_ENABLED
133 /** The nano ts of the last transfer. */
134 uint64_t u64LastTransferTS;
135 /** The nano ts of the last receive. */
136 uint64_t u64LastReceiveTS;
137#endif
138} DRVTAP, *PDRVTAP;
139
140
141/** Converts a pointer to TAP::INetworkConnector to a PRDVTAP. */
142#define PDMINETWORKCONNECTOR_2_DRVTAP(pInterface) ( (PDRVTAP)((uintptr_t)pInterface - RT_OFFSETOF(DRVTAP, INetworkConnector)) )
143
144
145/*******************************************************************************
146* Internal Functions *
147*******************************************************************************/
148#ifdef RT_OS_SOLARIS
149# ifdef VBOX_WITH_CROSSBOW
150static int SolarisOpenVNIC(PDRVTAP pData);
151static int SolarisDLPIErr2VBoxErr(int rc);
152# else
153static int SolarisTAPAttach(PDRVTAP pData);
154# endif
155#endif
156
157
158/**
159 * Send data to the network.
160 *
161 * @returns VBox status code.
162 * @param pInterface Pointer to the interface structure containing the called function pointer.
163 * @param pvBuf Data to send.
164 * @param cb Number of bytes to send.
165 * @thread EMT
166 */
167static DECLCALLBACK(int) drvTAPSend(PPDMINETWORKCONNECTOR pInterface, const void *pvBuf, size_t cb)
168{
169 PDRVTAP pData = PDMINETWORKCONNECTOR_2_DRVTAP(pInterface);
170 STAM_COUNTER_INC(&pData->StatPktSent);
171 STAM_COUNTER_ADD(&pData->StatPktSentBytes, cb);
172 STAM_PROFILE_START(&pData->StatTransmit, a);
173
174#ifdef LOG_ENABLED
175 uint64_t u64Now = RTTimeProgramNanoTS();
176 LogFlow(("drvTAPSend: %-4d bytes at %llu ns deltas: r=%llu t=%llu\n",
177 cb, u64Now, u64Now - pData->u64LastReceiveTS, u64Now - pData->u64LastTransferTS));
178 pData->u64LastTransferTS = u64Now;
179#endif
180 Log2(("drvTAPSend: pvBuf=%p cb=%#x\n"
181 "%.*Vhxd\n",
182 pvBuf, cb, cb, pvBuf));
183
184 int rc = RTFileWrite(pData->FileDevice, pvBuf, cb, NULL);
185
186 STAM_PROFILE_STOP(&pData->StatTransmit, a);
187 AssertRC(rc);
188 return rc;
189}
190
191
192/**
193 * Set promiscuous mode.
194 *
195 * This is called when the promiscuous mode is set. This means that there doesn't have
196 * to be a mode change when it's called.
197 *
198 * @param pInterface Pointer to the interface structure containing the called function pointer.
199 * @param fPromiscuous Set if the adaptor is now in promiscuous mode. Clear if it is not.
200 * @thread EMT
201 */
202static DECLCALLBACK(void) drvTAPSetPromiscuousMode(PPDMINETWORKCONNECTOR pInterface, bool fPromiscuous)
203{
204 LogFlow(("drvTAPSetPromiscuousMode: fPromiscuous=%d\n", fPromiscuous));
205 /* nothing to do */
206}
207
208
209/**
210 * Notification on link status changes.
211 *
212 * @param pInterface Pointer to the interface structure containing the called function pointer.
213 * @param enmLinkState The new link state.
214 * @thread EMT
215 */
216static DECLCALLBACK(void) drvTAPNotifyLinkChanged(PPDMINETWORKCONNECTOR pInterface, PDMNETWORKLINKSTATE enmLinkState)
217{
218 LogFlow(("drvNATNotifyLinkChanged: enmLinkState=%d\n", enmLinkState));
219 /** @todo take action on link down and up. Stop the polling and such like. */
220}
221
222
223/**
224 * Asynchronous I/O thread for handling receive.
225 *
226 * @returns VINF_SUCCESS (ignored).
227 * @param Thread Thread handle.
228 * @param pvUser Pointer to a DRVTAP structure.
229 */
230static DECLCALLBACK(int) drvTAPAsyncIoThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
231{
232 PDRVTAP pData = PDMINS2DATA(pDrvIns, PDRVTAP);
233 LogFlow(("drvTAPAsyncIoThread: pData=%p\n", pData));
234
235 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
236 return VINF_SUCCESS;
237
238 STAM_PROFILE_ADV_START(&pData->StatReceive, a);
239
240 /*
241 * Polling loop.
242 */
243 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
244 {
245 /*
246 * Wait for something to become available.
247 */
248 struct pollfd aFDs[2];
249 aFDs[0].fd = pData->FileDevice;
250 aFDs[0].events = POLLIN | POLLPRI;
251 aFDs[0].revents = 0;
252 aFDs[1].fd = pData->PipeRead;
253 aFDs[1].events = POLLIN | POLLPRI | POLLERR | POLLHUP;
254 aFDs[1].revents = 0;
255 STAM_PROFILE_ADV_STOP(&pData->StatReceive, a);
256 errno=0;
257 int rc = poll(&aFDs[0], ELEMENTS(aFDs), -1 /* infinite */);
258
259 /* this might have changed in the meantime */
260 if (pThread->enmState != PDMTHREADSTATE_RUNNING)
261 break;
262
263 STAM_PROFILE_ADV_START(&pData->StatReceive, a);
264 if ( rc > 0
265 && (aFDs[0].revents & (POLLIN | POLLPRI))
266 && !aFDs[1].revents)
267 {
268 /*
269 * Read the frame.
270 */
271 char achBuf[4096];
272 size_t cbRead = 0;
273#ifdef VBOX_WITH_CROSSBOW
274 cbRead = sizeof(achBuf);
275 rc = dlpi_recv(pData->pDeviceHandle, NULL, NULL, achBuf, &cbRead, -1, NULL);
276 rc = RT_LIKELY(rc == DLPI_SUCCESS) ? VINF_SUCCESS : SolarisDLPIErr2VBoxErr(rc);
277#else
278 /** @note At least on Linux we will never receive more than one network packet
279 * after poll() returned successfully. I don't know why but a second
280 * RTFileRead() operation will return with VERR_TRY_AGAIN in any case. */
281 rc = RTFileRead(pData->FileDevice, achBuf, sizeof(achBuf), &cbRead);
282#endif
283 if (VBOX_SUCCESS(rc))
284 {
285 AssertMsg(cbRead <= 1536, ("cbRead=%d\n", cbRead));
286
287 /*
288 * Wait for the device to have space for this frame.
289 * Most guests use frame-sized receive buffers, hence non-zero cbMax
290 * automatically means there is enough room for entire frame. Some
291 * guests (eg. Solaris) use large chains of small receive buffers
292 * (each 128 or so bytes large). We will still start receiving as soon
293 * as cbMax is non-zero because:
294 * - it would be quite expensive for pfnCanReceive to accurately
295 * determine free receive buffer space
296 * - if we were waiting for enough free buffers, there is a risk
297 * of deadlocking because the guest could be waiting for a receive
298 * overflow error to allocate more receive buffers
299 */
300 STAM_PROFILE_ADV_STOP(&pData->StatReceive, a);
301 int rc = pData->pPort->pfnWaitReceiveAvail(pData->pPort, RT_INDEFINITE_WAIT);
302 STAM_PROFILE_ADV_START(&pData->StatReceive, a);
303 if (RT_FAILURE(rc))
304 break;
305
306 /*
307 * Pass the data up.
308 */
309#ifdef LOG_ENABLED
310 uint64_t u64Now = RTTimeProgramNanoTS();
311 LogFlow(("drvTAPAsyncIoThread: %-4d bytes at %llu ns deltas: r=%llu t=%llu\n",
312 cbRead, u64Now, u64Now - pData->u64LastReceiveTS, u64Now - pData->u64LastTransferTS));
313 pData->u64LastReceiveTS = u64Now;
314#endif
315 Log2(("drvTAPAsyncIoThread: cbRead=%#x\n" "%.*Vhxd\n", cbRead, cbRead, achBuf));
316 STAM_COUNTER_INC(&pData->StatPktRecv);
317 STAM_COUNTER_ADD(&pData->StatPktRecvBytes, cbRead);
318 rc = pData->pPort->pfnReceive(pData->pPort, achBuf, cbRead);
319 AssertRC(rc);
320 }
321 else
322 {
323 LogFlow(("drvTAPAsyncIoThread: RTFileRead -> %Vrc\n", rc));
324 if (rc == VERR_INVALID_HANDLE)
325 break;
326 RTThreadYield();
327 }
328 }
329 else if ( rc > 0
330 && aFDs[1].revents)
331 {
332 LogFlow(("drvTAPAsyncIoThread: Control message: enmState=%d revents=%#x\n", pThread->enmState, aFDs[1].revents));
333 if (aFDs[1].revents & (POLLHUP | POLLERR | POLLNVAL))
334 break;
335
336 /* drain the pipe */
337 char ch;
338 size_t cbRead;
339 RTFileRead(pData->PipeRead, &ch, 1, &cbRead);
340 }
341 else
342 {
343 /*
344 * poll() failed for some reason. Yield to avoid eating too much CPU.
345 *
346 * EINTR errors have been seen frequently. They should be harmless, even
347 * if they are not supposed to occur in our setup.
348 */
349 if (errno == EINTR)
350 Log(("rc=%d revents=%#x,%#x errno=%p %s\n", rc, aFDs[0].revents, aFDs[1].revents, errno, strerror(errno)));
351 else
352 AssertMsgFailed(("rc=%d revents=%#x,%#x errno=%p %s\n", rc, aFDs[0].revents, aFDs[1].revents, errno, strerror(errno)));
353 RTThreadYield();
354 }
355 }
356
357
358 LogFlow(("drvTAPAsyncIoThread: returns %Vrc\n", VINF_SUCCESS));
359 STAM_PROFILE_ADV_STOP(&pData->StatReceive, a);
360 return VINF_SUCCESS;
361}
362
363
364/**
365 * Unblock the send thread so it can respond to a state change.
366 *
367 * @returns VBox status code.
368 * @param pDevIns The pcnet device instance.
369 * @param pThread The send thread.
370 */
371static DECLCALLBACK(int) drvTapAsyncIoWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
372{
373 PDRVTAP pData = PDMINS2DATA(pDrvIns, PDRVTAP);
374
375 int rc = RTFileWrite(pData->PipeWrite, "", 1, NULL);
376 AssertRC(rc);
377
378 return VINF_SUCCESS;
379}
380
381
382#if defined(RT_OS_SOLARIS)
383/**
384 * Calls OS-specific TAP setup application/script.
385 *
386 * @returns VBox error code.
387 * @param pData The instance data.
388 */
389static int drvTAPSetupApplication(PDRVTAP pData)
390{
391 char szCommand[4096];
392
393#ifdef VBOX_WITH_CROSSBOW
394 /* Convert MAC address bytes to string (required by Solaris' dladm). */
395 char *pszHex = "0123456789abcdef";
396 uint8_t *pMacAddr8 = pData->MacAddress.au8;
397 char szMacAddress[3 * sizeof(PDMMAC)];
398 for (unsigned int i = 0; i < sizeof(PDMMAC); i++)
399 {
400 szMacAddress[3 * i] = pszHex[((*pMacAddr8 >> 4) & 0x0f)];
401 szMacAddress[3 * i + 1] = pszHex[(*pMacAddr8 & 0x0f)];
402 szMacAddress[3 * i + 2] = ':';
403 *pMacAddr8++;
404 }
405 szMacAddress[sizeof(szMacAddress) - 1] = 0;
406
407 RTStrPrintf(szCommand, sizeof(szCommand), "%s %s %s", pData->pszSetupApplication,
408 szMacAddress, pData->fStatic ? pData->pszDeviceName : "");
409#else
410 RTStrPrintf(szCommand, sizeof(szCommand), "%s %s", pData->pszSetupApplication,
411 pData->fStatic ? pData->pszDeviceName : "");
412#endif
413
414 /* Pipe open the setup application. */
415 Log2(("Starting TAP setup application: %s\n", szCommand));
416 FILE* pfSetupHandle = popen(szCommand, "r");
417 if (pfSetupHandle == 0)
418 {
419 LogRel(("TAP#%d: Failed to run TAP setup application: %s\n", pData->pDrvIns->iInstance,
420 pData->pszSetupApplication, strerror(errno)));
421 return VERR_HOSTIF_INIT_FAILED;
422 }
423 if (!pData->fStatic)
424 {
425 /* Obtain device name from setup application. */
426 char acBuffer[64];
427 size_t cBufSize;
428 fgets(acBuffer, sizeof(acBuffer), pfSetupHandle);
429 cBufSize = strlen(acBuffer);
430 /* The script must return the name of the interface followed by a carriage return as the
431 first line of its output. We need a null-terminated string. */
432 if ((cBufSize < 2) || (acBuffer[cBufSize - 1] != '\n'))
433 {
434 pclose(pfSetupHandle);
435 LogRel(("The TAP interface setup script did not return the name of a TAP device.\n"));
436 return VERR_HOSTIF_INIT_FAILED;
437 }
438 /* Overwrite the terminating newline character. */
439 acBuffer[cBufSize - 1] = 0;
440 RTStrAPrintf(&pData->pszDeviceName, "%s", acBuffer);
441 }
442 int rc = pclose(pfSetupHandle);
443 if (!WIFEXITED(rc))
444 {
445 LogRel(("The TAP interface setup script terminated abnormally.\n"));
446 return VERR_HOSTIF_INIT_FAILED;
447 }
448 if (WEXITSTATUS(rc) != 0)
449 {
450 LogRel(("The TAP interface setup script returned a non-zero exit code.\n"));
451 return VERR_HOSTIF_INIT_FAILED;
452 }
453 return VINF_SUCCESS;
454}
455
456
457/**
458 * Calls OS-specific TAP terminate application/script.
459 *
460 * @returns VBox error code.
461 * @param pData The instance data.
462 */
463static int drvTAPTerminateApplication(PDRVTAP pData)
464{
465 char *pszArgs[3];
466 pszArgs[0] = pData->pszTerminateApplication;
467 pszArgs[1] = pData->pszDeviceName;
468 pszArgs[2] = NULL;
469
470 Log2(("Starting TAP terminate application: %s %s\n", pData->pszTerminateApplication, pData->pszDeviceName));
471 RTPROCESS pid = NIL_RTPROCESS;
472 int rc = RTProcCreate(pszArgs[0], pszArgs, RTENV_DEFAULT, 0, &pid);
473 if (RT_SUCCESS(rc))
474 {
475 RTPROCSTATUS Status;
476 rc = RTProcWait(pid, 0, &Status);
477 if (RT_SUCCESS(rc))
478 {
479 if ( Status.iStatus == 0
480 && Status.enmReason == RTPROCEXITREASON_NORMAL)
481 return VINF_SUCCESS;
482
483 LogRel(("TAP#%d: Error running TAP terminate application: %s\n", pData->pDrvIns->iInstance, pData->pszTerminateApplication));
484 }
485 else
486 LogRel(("TAP#%d: RTProcWait failed for: %s\n", pData->pDrvIns->iInstance, pData->pszTerminateApplication));
487 }
488 else
489 {
490 /* Bad. RTProcCreate() failed! */
491 LogRel(("TAP#%d: Failed to fork() process for running TAP terminate application: %s\n", pData->pDrvIns->iInstance,
492 pData->pszTerminateApplication, strerror(errno)));
493 }
494 return VERR_HOSTIF_TERM_FAILED;
495}
496
497#endif /* RT_OS_SOLARIS */
498
499
500#ifdef RT_OS_SOLARIS
501# ifdef VBOX_WITH_CROSSBOW
502/**
503 * Crossbow: Open & configure the virtual NIC.
504 *
505 * @returns VBox error code.
506 * @param pData The instance data.
507 */
508static int SolarisOpenVNIC(PDRVTAP pData)
509{
510 /*
511 * Open & bind the NIC using the datalink provider routine.
512 */
513 int rc = dlpi_open(pData->pszDeviceName, &pData->pDeviceHandle, DLPI_RAW);
514 if (rc != DLPI_SUCCESS)
515 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
516 N_("Failed to open VNIC \"%s\" in raw mode"), pData->pszDeviceName);
517
518 dlpi_info_t vnicInfo;
519 rc = dlpi_info(pData->pDeviceHandle, &vnicInfo, 0);
520 if (rc == DLPI_SUCCESS)
521 {
522 if (vnicInfo.di_mactype == DL_ETHER)
523 {
524 rc = dlpi_bind(pData->pDeviceHandle, DLPI_ANY_SAP, NULL);
525 if (rc == DLPI_SUCCESS)
526 {
527 rc = dlpi_set_physaddr(pData->pDeviceHandle, DL_CURR_PHYS_ADDR, &pData->MacAddress, ETHERADDRL);
528 if (rc == DLPI_SUCCESS)
529 {
530 rc = dlpi_promiscon(pData->pDeviceHandle, DL_PROMISC_SAP);
531 if (rc == DLPI_SUCCESS)
532 {
533 /* Need to use DL_PROMIS_PHYS (not multicast) as we cannot be sure what the guest needs. */
534 rc = dlpi_promiscon(pData->pDeviceHandle, DL_PROMISC_PHYS);
535 if (rc == DLPI_SUCCESS)
536 {
537 pData->FileDevice = dlpi_fd(pData->pDeviceHandle);
538 if (pData->FileDevice >= 0)
539 {
540 Log(("SolarisOpenVNIC: %s -> %d\n", pData->pszDeviceName, pData->FileDevice));
541 return VINF_SUCCESS;
542 }
543
544 rc = PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
545 N_("Failed to obtain file descriptor for VNIC"));
546 }
547 else
548 rc = PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
549 N_("Failed to set appropriate promiscous mode"));
550 }
551 else
552 rc = PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
553 N_("Failed to activate promiscous mode for VNIC"));
554 }
555 else
556 rc = PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
557 N_("Failed to set physical address for VNIC"));
558 }
559 else
560 rc = PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
561 N_("Failed to bind VNIC"));
562 }
563 else
564 rc = PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
565 N_("VNIC type is not ethernet"));
566 }
567 else
568 rc = PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
569 N_("Failed to obtain VNIC info"));
570 dlpi_close(pData->pDeviceHandle);
571 return rc;
572}
573
574
575/**
576 * Crossbow: Converts a Solaris DLPI error code to a VBox error code.
577 *
578 * @returns corresponding VBox error code.
579 * @param rc DLPI error code (DLPI_* defines).
580 */
581static int SolarisDLPIErr2VBoxErr(int rc)
582{
583 switch (rc)
584 {
585 case DLPI_SUCCESS: return VINF_SUCCESS;
586 case DLPI_EINVAL: return VERR_INVALID_PARAMETER;
587 case DLPI_ELINKNAMEINVAL: return VERR_INVALID_NAME;
588 case DLPI_EINHANDLE: return VERR_INVALID_HANDLE;
589 case DLPI_ETIMEDOUT: return VERR_TIMEOUT;
590 case DLPI_FAILURE: return VERR_GENERAL_FAILURE;
591
592 case DLPI_EVERNOTSUP:
593 case DLPI_EMODENOTSUP:
594 case DLPI_ERAWNOTSUP:
595 /* case DLPI_ENOTENOTSUP: */
596 case DLPI_EUNAVAILSAP: return VERR_NOT_SUPPORTED;
597
598 /* Define VBox error codes for these, if really needed. */
599 case DLPI_ENOLINK:
600 case DLPI_EBADLINK:
601 /* case DLPI_ENOTEIDINVAL: */
602 case DLPI_EBADMSG:
603 case DLPI_ENOTSTYLE2: return VERR_GENERAL_FAILURE;
604 }
605
606 AssertMsgFailed(("SolarisDLPIErr2VBoxErr: Unhandled error %d\n", rc));
607 return VERR_UNRESOLVED_ERROR;
608}
609
610# else /* VBOX_WITH_CROSSBOW */
611
612/** From net/if_tun.h, installed by Universal TUN/TAP driver */
613# define TUNNEWPPA (('T'<<16) | 0x0001)
614/** Whether to enable ARP for TAP. */
615# define VBOX_SOLARIS_TAP_ARP 1
616
617/**
618 * Creates/Attaches TAP device to IP.
619 *
620 * @returns VBox error code.
621 * @param pData The instance data.
622 */
623static DECLCALLBACK(int) SolarisTAPAttach(PDRVTAP pData)
624{
625 LogFlow(("SolarisTapAttach: pData=%p\n", pData));
626
627
628 int IPFileDes = open("/dev/udp", O_RDWR, 0);
629 if (IPFileDes < 0)
630 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
631 N_("Failed to open /dev/udp. errno=%d"), errno);
632
633 int TapFileDes = open("/dev/tap", O_RDWR, 0);
634 if (TapFileDes < 0)
635 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
636 N_("Failed to open /dev/tap for TAP. errno=%d"), errno);
637
638 /* Use the PPA from the ifname if possible (e.g "tap2", then use 2 as PPA) */
639 int iPPA = -1;
640 if (pData->pszDeviceName)
641 {
642 size_t cch = strlen(pData->pszDeviceName);
643 if (cch > 1 && isdigit(pData->pszDeviceName[cch - 1]) != 0)
644 iPPA = pData->pszDeviceName[cch - 1] - '0';
645 }
646
647 struct strioctl ioIF;
648 ioIF.ic_cmd = TUNNEWPPA;
649 ioIF.ic_len = sizeof(iPPA);
650 ioIF.ic_dp = (char *)(&iPPA);
651 ioIF.ic_timout = 0;
652 iPPA = ioctl(TapFileDes, I_STR, &ioIF);
653 if (iPPA < 0)
654 {
655 close(TapFileDes);
656 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_IOCTL, RT_SRC_POS,
657 N_("Failed to get new interface. errno=%d"), errno);
658 }
659
660 int InterfaceFD = open("/dev/tap", O_RDWR, 0);
661 if (!InterfaceFD)
662 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_PDM_HIF_OPEN_FAILED, RT_SRC_POS,
663 N_("Failed to open interface /dev/tap. errno=%d"), errno);
664
665 if (ioctl(InterfaceFD, I_PUSH, "ip") == -1)
666 {
667 close(InterfaceFD);
668 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_IOCTL, RT_SRC_POS,
669 N_("Failed to push IP. errno=%d"), errno);
670 }
671
672 struct lifreq ifReq;
673 memset(&ifReq, 0, sizeof(ifReq));
674 if (ioctl(InterfaceFD, SIOCGLIFFLAGS, &ifReq) == -1)
675 LogRel(("TAP#%d: Failed to get interface flags.\n", pData->pDrvIns->iInstance));
676
677 ifReq.lifr_ppa = iPPA;
678 RTStrPrintf (ifReq.lifr_name, sizeof(ifReq.lifr_name), pData->pszDeviceName);
679
680 if (ioctl(InterfaceFD, SIOCSLIFNAME, &ifReq) == -1)
681 LogRel(("TAP#%d: Failed to set PPA. errno=%d\n", pData->pDrvIns->iInstance, errno));
682
683 if (ioctl(InterfaceFD, SIOCGLIFFLAGS, &ifReq) == -1)
684 LogRel(("TAP#%d: Failed to get interface flags after setting PPA. errno=%d\n", pData->pDrvIns->iInstance, errno));
685
686#ifdef VBOX_SOLARIS_TAP_ARP
687 /* Interface */
688 if (ioctl(InterfaceFD, I_PUSH, "arp") == -1)
689 LogRel(("TAP#%d: Failed to push ARP to Interface FD. errno=%d\n", pData->pDrvIns->iInstance, errno));
690
691 /* IP */
692 if (ioctl(IPFileDes, I_POP, NULL) == -1)
693 LogRel(("TAP#%d: Failed I_POP from IP FD. errno=%d\n", pData->pDrvIns->iInstance, errno));
694
695 if (ioctl(IPFileDes, I_PUSH, "arp") == -1)
696 LogRel(("TAP#%d: Failed to push ARP to IP FD. errno=%d\n", pData->pDrvIns->iInstance, errno));
697
698 /* ARP */
699 int ARPFileDes = open("/dev/tap", O_RDWR, 0);
700 if (ARPFileDes < 0)
701 LogRel(("TAP#%d: Failed to open for /dev/tap for ARP. errno=%d", pData->pDrvIns->iInstance, errno));
702
703 if (ioctl(ARPFileDes, I_PUSH, "arp") == -1)
704 LogRel(("TAP#%d: Failed to push ARP to ARP FD. errno=%d\n", pData->pDrvIns->iInstance, errno));
705
706 ioIF.ic_cmd = SIOCSLIFNAME;
707 ioIF.ic_timout = 0;
708 ioIF.ic_len = sizeof(ifReq);
709 ioIF.ic_dp = (char *)&ifReq;
710 if (ioctl(ARPFileDes, I_STR, &ioIF) == -1)
711 LogRel(("TAP#%d: Failed to set interface name to ARP.\n", pData->pDrvIns->iInstance));
712#endif
713
714 /* We must use I_LINK and not I_PLINK as I_PLINK makes the link persistent.
715 * Then we would not be able unlink the interface if we reuse it.
716 * Even 'unplumb' won't work after that.
717 */
718 int IPMuxID = ioctl(IPFileDes, I_LINK, InterfaceFD);
719 if (IPMuxID == -1)
720 {
721 close(InterfaceFD);
722#ifdef VBOX_SOLARIS_TAP_ARP
723 close(ARPFileDes);
724#endif
725 LogRel(("TAP#%d: Cannot link TAP device to IP.\n", pData->pDrvIns->iInstance));
726 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_IOCTL, RT_SRC_POS,
727 N_("Failed to link TAP device to IP. Check TAP interface name. errno=%d"), errno);
728 }
729
730#ifdef VBOX_SOLARIS_TAP_ARP
731 int ARPMuxID = ioctl(IPFileDes, I_LINK, ARPFileDes);
732 if (ARPMuxID == -1)
733 LogRel(("TAP#%d: Failed to link TAP device to ARP\n", pData->pDrvIns->iInstance));
734
735 close(ARPFileDes);
736#endif
737 close(InterfaceFD);
738
739 /* Reuse ifReq */
740 memset(&ifReq, 0, sizeof(ifReq));
741 RTStrPrintf (ifReq.lifr_name, sizeof(ifReq.lifr_name), pData->pszDeviceName);
742 ifReq.lifr_ip_muxid = IPMuxID;
743#ifdef VBOX_SOLARIS_TAP_ARP
744 ifReq.lifr_arp_muxid = ARPMuxID;
745#endif
746
747 if (ioctl(IPFileDes, SIOCSLIFMUXID, &ifReq) == -1)
748 {
749#ifdef VBOX_SOLARIS_TAP_ARP
750 ioctl(IPFileDes, I_PUNLINK, ARPMuxID);
751#endif
752 ioctl(IPFileDes, I_PUNLINK, IPMuxID);
753 close(IPFileDes);
754 LogRel(("TAP#%d: Failed to set Mux ID.\n", pData->pDrvIns->iInstance));
755 return PDMDrvHlpVMSetError(pData->pDrvIns, VERR_HOSTIF_IOCTL, RT_SRC_POS,
756 N_("Failed to set Mux ID. Check TAP interface name. errno=%d"), errno);
757 }
758
759 pData->FileDevice = (RTFILE)TapFileDes;
760 pData->IPFileDevice = (RTFILE)IPFileDes;
761
762 return VINF_SUCCESS;
763}
764
765# endif /* VBOX_WITH_CROSSBOW */
766#endif /* RT_OS_SOLARIS */
767
768
769/**
770 * Queries an interface to the driver.
771 *
772 * @returns Pointer to interface.
773 * @returns NULL if the interface was not supported by the driver.
774 * @param pInterface Pointer to this interface structure.
775 * @param enmInterface The requested interface identification.
776 * @thread Any thread.
777 */
778static DECLCALLBACK(void *) drvTAPQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
779{
780 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
781 PDRVTAP pData = PDMINS2DATA(pDrvIns, PDRVTAP);
782 switch (enmInterface)
783 {
784 case PDMINTERFACE_BASE:
785 return &pDrvIns->IBase;
786 case PDMINTERFACE_NETWORK_CONNECTOR:
787 return &pData->INetworkConnector;
788 default:
789 return NULL;
790 }
791}
792
793
794/**
795 * Destruct a driver instance.
796 *
797 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
798 * resources can be freed correctly.
799 *
800 * @param pDrvIns The driver instance data.
801 */
802static DECLCALLBACK(void) drvTAPDestruct(PPDMDRVINS pDrvIns)
803{
804 LogFlow(("drvTAPDestruct\n"));
805 PDRVTAP pData = PDMINS2DATA(pDrvIns, PDRVTAP);
806
807 /*
808 * Terminate the control pipe.
809 */
810 if (pData->PipeWrite != NIL_RTFILE)
811 {
812 int rc = RTFileClose(pData->PipeWrite);
813 AssertRC(rc);
814 pData->PipeWrite = NIL_RTFILE;
815 }
816 if (pData->PipeRead != NIL_RTFILE)
817 {
818 int rc = RTFileClose(pData->PipeRead);
819 AssertRC(rc);
820 pData->PipeRead = NIL_RTFILE;
821 }
822
823#ifdef RT_OS_SOLARIS
824 /** @todo r=bird: This *does* need checking against ConsoleImpl2.cpp if used on non-solaris systems. */
825 if (pData->FileDevice != NIL_RTFILE)
826 {
827 int rc = RTFileClose(pData->FileDevice);
828 AssertRC(rc);
829 pData->FileDevice = NIL_RTFILE;
830 }
831
832# ifndef VBOX_WITH_CROSSBOW
833 if (pData->IPFileDevice != NIL_RTFILE)
834 {
835 int rc = RTFileClose(pData->IPFileDevice);
836 AssertRC(rc);
837 pData->IPFileDevice = NIL_RTFILE;
838 }
839# endif
840
841 /*
842 * Call TerminateApplication after closing the device otherwise
843 * TerminateApplication would not be able to unplumb it.
844 */
845 if (pData->pszTerminateApplication)
846 drvTAPTerminateApplication(pData);
847
848#endif /* RT_OS_SOLARIS */
849
850#ifdef RT_OS_SOLARIS
851 if (!pData->fStatic)
852 RTStrFree(pData->pszDeviceName); /* allocated by drvTAPSetupApplication */
853 else
854 MMR3HeapFree(pData->pszDeviceName);
855#else
856 MMR3HeapFree(pData->pszDeviceName);
857#endif
858 MMR3HeapFree(pData->pszSetupApplication);
859 MMR3HeapFree(pData->pszTerminateApplication);
860}
861
862
863/**
864 * Construct a TAP network transport driver instance.
865 *
866 * @returns VBox status.
867 * @param pDrvIns The driver instance data.
868 * If the registration structure is needed, pDrvIns->pDrvReg points to it.
869 * @param pCfgHandle Configuration node handle for the driver. Use this to obtain the configuration
870 * of the driver instance. It's also found in pDrvIns->pCfgHandle, but like
871 * iInstance it's expected to be used a bit in this function.
872 */
873static DECLCALLBACK(int) drvTAPConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
874{
875 PDRVTAP pData = PDMINS2DATA(pDrvIns, PDRVTAP);
876
877 /*
878 * Init the static parts.
879 */
880 pData->pDrvIns = pDrvIns;
881 pData->FileDevice = NIL_RTFILE;
882 pData->pszDeviceName = NULL;
883#ifdef RT_OS_SOLARIS
884# ifdef VBOX_WITH_CROSSBOW
885 pData->pDeviceHandle = NULL;
886# else
887 pData->IPFileDevice = NIL_RTFILE;
888# endif
889 pData->fStatic = true;
890#endif
891 pData->pszSetupApplication = NULL;
892 pData->pszTerminateApplication = NULL;
893
894 /* IBase */
895 pDrvIns->IBase.pfnQueryInterface = drvTAPQueryInterface;
896 /* INetwork */
897 pData->INetworkConnector.pfnSend = drvTAPSend;
898 pData->INetworkConnector.pfnSetPromiscuousMode = drvTAPSetPromiscuousMode;
899 pData->INetworkConnector.pfnNotifyLinkChanged = drvTAPNotifyLinkChanged;
900
901 /*
902 * Validate the config.
903 */
904 if (!CFGMR3AreValuesValid(pCfgHandle, "Device\0InitProg\0TermProg\0FileHandle\0TAPSetupApplication\0TAPTerminateApplication\0MAC"))
905 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES, "");
906
907 /*
908 * Check that no-one is attached to us.
909 */
910 int rc = pDrvIns->pDrvHlp->pfnAttach(pDrvIns, NULL);
911 if (rc != VERR_PDM_NO_ATTACHED_DRIVER)
912 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_DRVINS_NO_ATTACH,
913 N_("Configuration error: Cannot attach drivers to the TAP driver"));
914
915 /*
916 * Query the network port interface.
917 */
918 pData->pPort = (PPDMINETWORKPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_NETWORK_PORT);
919 if (!pData->pPort)
920 return PDMDRV_SET_ERROR(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE,
921 N_("Configuration error: The above device/driver didn't export the network port interface"));
922
923 /*
924 * Read the configuration.
925 */
926#if defined(RT_OS_SOLARIS) /** @todo Other platforms' TAP code should be moved here from ConsoleImpl & VBoxBFE. */
927 rc = CFGMR3QueryStringAlloc(pCfgHandle, "TAPSetupApplication", &pData->pszSetupApplication);
928 if (VBOX_SUCCESS(rc))
929 {
930 if (!RTPathExists(pData->pszSetupApplication))
931 return PDMDrvHlpVMSetError(pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
932 N_("Invalid TAP setup program path: %s"), pData->pszSetupApplication);
933 }
934 else if (rc != VERR_CFGM_VALUE_NOT_FOUND)
935 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Configuration error: failed to query \"TAPTerminateApplication\""));
936
937 rc = CFGMR3QueryStringAlloc(pCfgHandle, "TAPTerminateApplication", &pData->pszTerminateApplication);
938 if (VBOX_SUCCESS(rc))
939 {
940 if (!RTPathExists(pData->pszTerminateApplication))
941 return PDMDrvHlpVMSetError(pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
942 N_("Invalid TAP terminate program path: %s"), pData->pszTerminateApplication);
943 }
944 else if (rc != VERR_CFGM_VALUE_NOT_FOUND)
945 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Configuration error: failed to query \"TAPTerminateApplication\""));
946
947# ifdef VBOX_WITH_CROSSBOW
948 rc = CFGMR3QueryBytes(pCfgHandle, "MAC", &pData->MacAddress, sizeof(pData->MacAddress));
949 if (VBOX_FAILURE(rc))
950 return PDMDRV_SET_ERROR(pDrvIns, rc, N_("Configuration error: Failed to query \"MAC\""));
951# endif
952
953 rc = CFGMR3QueryStringAlloc(pCfgHandle, "Device", &pData->pszDeviceName);
954 if (VBOX_FAILURE(rc))
955 pData->fStatic = false;
956
957 /* Obtain the device name from the setup application (if none was specified). */
958 if (pData->pszSetupApplication)
959 {
960 rc = drvTAPSetupApplication(pData);
961 if (VBOX_FAILURE(rc))
962 return PDMDrvHlpVMSetError(pDrvIns, VERR_HOSTIF_INIT_FAILED, RT_SRC_POS,
963 N_("Error running TAP setup application. rc=%d"), rc);
964 }
965
966 /*
967 * Do the setup.
968 */
969# ifdef VBOX_WITH_CROSSBOW
970 rc = SolarisOpenVNIC(pData);
971# else
972 rc = SolarisTAPAttach(pData);
973# endif
974 if (VBOX_FAILURE(rc))
975 return rc;
976
977#else /* !RT_OS_SOLARIS */
978
979 int32_t iFile;
980 rc = CFGMR3QueryS32(pCfgHandle, "FileHandle", &iFile);
981 if (VBOX_FAILURE(rc))
982 return PDMDRV_SET_ERROR(pDrvIns, rc,
983 N_("Configuration error: Query for \"FileHandle\" 32-bit signed integer failed"));
984 pData->FileDevice = (RTFILE)iFile;
985 if (!RTFileIsValid(pData->FileDevice))
986 return PDMDrvHlpVMSetError(pDrvIns, VERR_INVALID_HANDLE, RT_SRC_POS,
987 N_("The TAP file handle %RTfile is not valid"), pData->FileDevice);
988#endif /* !RT_OS_SOLARIS */
989
990 /*
991 * Make sure the descriptor is non-blocking and valid.
992 *
993 * We should actually query if it's a TAP device, but I haven't
994 * found any way to do that.
995 */
996 if (fcntl(pData->FileDevice, F_SETFL, O_NONBLOCK) == -1)
997 return PDMDrvHlpVMSetError(pDrvIns, VERR_HOSTIF_IOCTL, RT_SRC_POS,
998 N_("Configuration error: Failed to configure /dev/net/tun. errno=%d"), errno);
999 /** @todo determine device name. This can be done by reading the link /proc/<pid>/fd/<fd> */
1000 Log(("drvTAPContruct: %d (from fd)\n", pData->FileDevice));
1001 rc = VINF_SUCCESS;
1002
1003 /*
1004 * Create the control pipe.
1005 */
1006 int fds[2];
1007#ifdef RT_OS_L4
1008 /* XXX We need to tell the library which interface we are using */
1009 fds[0] = vboxrtLinuxFd2VBoxFd(VBOXRT_FT_TAP, 0);
1010#endif
1011 if (pipe(&fds[0]) != 0) /** @todo RTPipeCreate() or something... */
1012 {
1013 int rc = RTErrConvertFromErrno(errno);
1014 AssertRC(rc);
1015 return rc;
1016 }
1017 pData->PipeRead = fds[0];
1018 pData->PipeWrite = fds[1];
1019
1020 /*
1021 * Create the async I/O thread.
1022 */
1023 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pData->pThread, pData, drvTAPAsyncIoThread, drvTapAsyncIoWakeup, 128 * _1K, RTTHREADTYPE_IO, "TAP");
1024 AssertRCReturn(rc, rc);
1025
1026#ifdef VBOX_WITH_STATISTICS
1027 /*
1028 * Statistics.
1029 */
1030 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatPktSent, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of sent packets.", "/Drivers/TAP%d/Packets/Sent", pDrvIns->iInstance);
1031 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatPktSentBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Number of sent bytes.", "/Drivers/TAP%d/Bytes/Sent", pDrvIns->iInstance);
1032 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatPktRecv, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_OCCURENCES, "Number of received packets.", "/Drivers/TAP%d/Packets/Received", pDrvIns->iInstance);
1033 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatPktRecvBytes, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS, STAMUNIT_BYTES, "Number of received bytes.", "/Drivers/TAP%d/Bytes/Received", pDrvIns->iInstance);
1034 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatTransmit, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling packet transmit runs.", "/Drivers/TAP%d/Transmit", pDrvIns->iInstance);
1035 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatReceive, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS, STAMUNIT_TICKS_PER_CALL, "Profiling packet receive runs.", "/Drivers/TAP%d/Receive", pDrvIns->iInstance);
1036#endif /* VBOX_WITH_STATISTICS */
1037
1038 return rc;
1039}
1040
1041
1042/**
1043 * TAP network transport driver registration record.
1044 */
1045const PDMDRVREG g_DrvHostInterface =
1046{
1047 /* u32Version */
1048 PDM_DRVREG_VERSION,
1049 /* szDriverName */
1050 "HostInterface",
1051 /* pszDescription */
1052 "TAP Network Transport Driver",
1053 /* fFlags */
1054 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1055 /* fClass. */
1056 PDM_DRVREG_CLASS_NETWORK,
1057 /* cMaxInstances */
1058 ~0,
1059 /* cbInstance */
1060 sizeof(DRVTAP),
1061 /* pfnConstruct */
1062 drvTAPConstruct,
1063 /* pfnDestruct */
1064 drvTAPDestruct,
1065 /* pfnIOCtl */
1066 NULL,
1067 /* pfnPowerOn */
1068 NULL,
1069 /* pfnReset */
1070 NULL,
1071 /* pfnSuspend */
1072 NULL, /** @todo Do power on, suspend and resume handlers! */
1073 /* pfnResume */
1074 NULL,
1075 /* pfnDetach */
1076 NULL,
1077 /* pfnPowerOff */
1078 NULL
1079};
1080
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