VirtualBox

source: vbox/trunk/src/VBox/Devices/Serial/DrvHostSerial.cpp@ 37950

Last change on this file since 37950 was 37597, checked in by vboxsync, 13 years ago

darwin build fix

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 45.1 KB
Line 
1/* $Id: DrvHostSerial.cpp 37597 2011-06-22 20:54:05Z vboxsync $ */
2/** @file
3 * VBox stream I/O devices: Host serial driver
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19
20/*******************************************************************************
21* Header Files *
22*******************************************************************************/
23#define LOG_GROUP LOG_GROUP_DRV_HOST_SERIAL
24#include <VBox/vmm/pdm.h>
25#include <VBox/err.h>
26
27#include <VBox/log.h>
28#include <iprt/asm.h>
29#include <iprt/assert.h>
30#include <iprt/file.h>
31#include <iprt/mem.h>
32#include <iprt/pipe.h>
33#include <iprt/semaphore.h>
34#include <iprt/uuid.h>
35
36#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
37# include <errno.h>
38# ifdef RT_OS_SOLARIS
39# include <sys/termios.h>
40# else
41# include <termios.h>
42# endif
43# include <sys/types.h>
44# include <fcntl.h>
45# include <string.h>
46# include <unistd.h>
47# ifdef RT_OS_DARWIN
48# include <sys/select.h>
49# else
50# include <sys/poll.h>
51# endif
52# include <sys/ioctl.h>
53# include <pthread.h>
54
55# ifdef RT_OS_LINUX
56/*
57 * TIOCM_LOOP is not defined in the above header files for some reason but in asm/termios.h.
58 * But inclusion of this file however leads to compilation errors because of redefinition of some
59 * structs. That's why it is defined here until a better solution is found.
60 */
61# ifndef TIOCM_LOOP
62# define TIOCM_LOOP 0x8000
63# endif
64/* For linux custom baudrate code we also need serial_struct */
65# include <linux/serial.h>
66# endif /* linux */
67
68#elif defined(RT_OS_WINDOWS)
69# include <Windows.h>
70#endif
71
72#include "VBoxDD.h"
73
74
75/*******************************************************************************
76* Structures and Typedefs *
77*******************************************************************************/
78
79/**
80 * Char driver instance data.
81 *
82 * @implements PDMICHARCONNECTOR
83 */
84typedef struct DRVHOSTSERIAL
85{
86 /** Pointer to the driver instance structure. */
87 PPDMDRVINS pDrvIns;
88 /** Pointer to the char port interface of the driver/device above us. */
89 PPDMICHARPORT pDrvCharPort;
90 /** Our char interface. */
91 PDMICHARCONNECTOR ICharConnector;
92 /** Receive thread. */
93 PPDMTHREAD pRecvThread;
94 /** Send thread. */
95 PPDMTHREAD pSendThread;
96 /** Status lines monitor thread. */
97 PPDMTHREAD pMonitorThread;
98 /** Send event semaphore */
99 RTSEMEVENT SendSem;
100
101 /** the device path */
102 char *pszDevicePath;
103
104#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
105 /** the device handle */
106 RTFILE hDeviceFile;
107# ifdef RT_OS_DARWIN
108 /** The device handle used for reading.
109 * Used to prevent the read select from blocking the writes. */
110 RTFILE hDeviceFileR;
111# endif
112 /** The read end of the control pipe */
113 RTPIPE hWakeupPipeR;
114 /** The write end of the control pipe */
115 RTPIPE hWakeupPipeW;
116# ifndef RT_OS_LINUX
117 /** The current line status.
118 * Used by the polling version of drvHostSerialMonitorThread. */
119 int fStatusLines;
120# endif
121#elif defined(RT_OS_WINDOWS)
122 /** the device handle */
123 HANDLE hDeviceFile;
124 /** The event semaphore for waking up the receive thread */
125 HANDLE hHaltEventSem;
126 /** The event semaphore for overlapped receiving */
127 HANDLE hEventRecv;
128 /** For overlapped receiving */
129 OVERLAPPED overlappedRecv;
130 /** The event semaphore for overlapped sending */
131 HANDLE hEventSend;
132 /** For overlapped sending */
133 OVERLAPPED overlappedSend;
134#endif
135
136 /** Internal send FIFO queue */
137 uint8_t volatile u8SendByte;
138 bool volatile fSending;
139 uint8_t Alignment[2];
140
141 /** Read/write statistics */
142 STAMCOUNTER StatBytesRead;
143 STAMCOUNTER StatBytesWritten;
144#ifdef RT_OS_DARWIN
145 /** The number of bytes we've dropped because the send queue
146 * was full. */
147 STAMCOUNTER StatSendOverflows;
148#endif
149} DRVHOSTSERIAL, *PDRVHOSTSERIAL;
150
151
152/** Converts a pointer to DRVCHAR::ICharConnector to a PDRVHOSTSERIAL. */
153#define PDMICHAR_2_DRVHOSTSERIAL(pInterface) RT_FROM_MEMBER(pInterface, DRVHOSTSERIAL, ICharConnector)
154
155
156/* -=-=-=-=- IBase -=-=-=-=- */
157
158/**
159 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
160 */
161static DECLCALLBACK(void *) drvHostSerialQueryInterface(PPDMIBASE pInterface, const char *pszIID)
162{
163 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
164 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
165
166 PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
167 PDMIBASE_RETURN_INTERFACE(pszIID, PDMICHARCONNECTOR, &pThis->ICharConnector);
168 return NULL;
169}
170
171
172/* -=-=-=-=- ICharConnector -=-=-=-=- */
173
174/** @copydoc PDMICHARCONNECTOR::pfnWrite */
175static DECLCALLBACK(int) drvHostSerialWrite(PPDMICHARCONNECTOR pInterface, const void *pvBuf, size_t cbWrite)
176{
177 PDRVHOSTSERIAL pThis = PDMICHAR_2_DRVHOSTSERIAL(pInterface);
178 const uint8_t *pbBuffer = (const uint8_t *)pvBuf;
179
180 LogFlow(("%s: pvBuf=%#p cbWrite=%d\n", __FUNCTION__, pvBuf, cbWrite));
181
182 for (uint32_t i = 0; i < cbWrite; i++)
183 {
184 if (ASMAtomicXchgBool(&pThis->fSending, true))
185 return VERR_BUFFER_OVERFLOW;
186
187 pThis->u8SendByte = pbBuffer[i];
188 RTSemEventSignal(pThis->SendSem);
189 STAM_COUNTER_INC(&pThis->StatBytesWritten);
190 }
191 return VINF_SUCCESS;
192}
193
194static DECLCALLBACK(int) drvHostSerialSetParameters(PPDMICHARCONNECTOR pInterface, unsigned Bps, char chParity, unsigned cDataBits, unsigned cStopBits)
195{
196 PDRVHOSTSERIAL pThis = PDMICHAR_2_DRVHOSTSERIAL(pInterface);
197#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
198 struct termios *termiosSetup;
199 int baud_rate;
200#elif defined(RT_OS_WINDOWS)
201 LPDCB comSetup;
202#endif
203
204 LogFlow(("%s: Bps=%u chParity=%c cDataBits=%u cStopBits=%u\n", __FUNCTION__, Bps, chParity, cDataBits, cStopBits));
205
206#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS)
207 termiosSetup = (struct termios *)RTMemTmpAllocZ(sizeof(struct termios));
208
209 /* Enable receiver */
210 termiosSetup->c_cflag |= (CLOCAL | CREAD);
211
212 switch (Bps)
213 {
214 case 50:
215 baud_rate = B50;
216 break;
217 case 75:
218 baud_rate = B75;
219 break;
220 case 110:
221 baud_rate = B110;
222 break;
223 case 134:
224 baud_rate = B134;
225 break;
226 case 150:
227 baud_rate = B150;
228 break;
229 case 200:
230 baud_rate = B200;
231 break;
232 case 300:
233 baud_rate = B300;
234 break;
235 case 600:
236 baud_rate = B600;
237 break;
238 case 1200:
239 baud_rate = B1200;
240 break;
241 case 1800:
242 baud_rate = B1800;
243 break;
244 case 2400:
245 baud_rate = B2400;
246 break;
247 case 4800:
248 baud_rate = B4800;
249 break;
250 case 9600:
251 baud_rate = B9600;
252 break;
253 case 19200:
254 baud_rate = B19200;
255 break;
256 case 38400:
257 baud_rate = B38400;
258 break;
259 case 57600:
260 baud_rate = B57600;
261 break;
262 case 115200:
263 baud_rate = B115200;
264 break;
265 default:
266#ifdef RT_OS_LINUX
267 struct serial_struct serialStruct;
268 if (ioctl(RTFileToNative(pThis->hDeviceFile), TIOCGSERIAL, &serialStruct) != -1)
269 {
270 serialStruct.custom_divisor = serialStruct.baud_base / Bps;
271 if (!serialStruct.custom_divisor)
272 serialStruct.custom_divisor = 1;
273 serialStruct.flags &= ~ASYNC_SPD_MASK;
274 serialStruct.flags |= ASYNC_SPD_CUST;
275 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCSSERIAL, &serialStruct);
276 baud_rate = B38400;
277 }
278 else
279 baud_rate = B9600;
280#else /* !RT_OS_LINUX */
281 baud_rate = B9600;
282#endif /* !RT_OS_LINUX */
283 }
284
285 cfsetispeed(termiosSetup, baud_rate);
286 cfsetospeed(termiosSetup, baud_rate);
287
288 switch (chParity)
289 {
290 case 'E':
291 termiosSetup->c_cflag |= PARENB;
292 break;
293 case 'O':
294 termiosSetup->c_cflag |= (PARENB | PARODD);
295 break;
296 case 'N':
297 break;
298 default:
299 break;
300 }
301
302 switch (cDataBits)
303 {
304 case 5:
305 termiosSetup->c_cflag |= CS5;
306 break;
307 case 6:
308 termiosSetup->c_cflag |= CS6;
309 break;
310 case 7:
311 termiosSetup->c_cflag |= CS7;
312 break;
313 case 8:
314 termiosSetup->c_cflag |= CS8;
315 break;
316 default:
317 break;
318 }
319
320 switch (cStopBits)
321 {
322 case 2:
323 termiosSetup->c_cflag |= CSTOPB;
324 default:
325 break;
326 }
327
328 /* set serial port to raw input */
329 termiosSetup->c_lflag &= ~(ICANON | ECHO | ECHOE | ECHONL | ECHOK | ISIG | IEXTEN);
330
331 tcsetattr(RTFileToNative(pThis->hDeviceFile), TCSANOW, termiosSetup);
332 RTMemTmpFree(termiosSetup);
333
334#ifdef RT_OS_LINUX
335 /*
336 * XXX In Linux, if a thread calls tcsetattr while the monitor thread is
337 * waiting in ioctl for a modem status change then 8250.c wrongly disables
338 * modem irqs and so the monitor thread never gets released. The workaround
339 * is to send a signal after each tcsetattr.
340 */
341 RTThreadPoke(pThis->pMonitorThread->Thread);
342#endif
343
344#elif defined(RT_OS_WINDOWS)
345 comSetup = (LPDCB)RTMemTmpAllocZ(sizeof(DCB));
346
347 comSetup->DCBlength = sizeof(DCB);
348
349 switch (Bps)
350 {
351 case 110:
352 comSetup->BaudRate = CBR_110;
353 break;
354 case 300:
355 comSetup->BaudRate = CBR_300;
356 break;
357 case 600:
358 comSetup->BaudRate = CBR_600;
359 break;
360 case 1200:
361 comSetup->BaudRate = CBR_1200;
362 break;
363 case 2400:
364 comSetup->BaudRate = CBR_2400;
365 break;
366 case 4800:
367 comSetup->BaudRate = CBR_4800;
368 break;
369 case 9600:
370 comSetup->BaudRate = CBR_9600;
371 break;
372 case 14400:
373 comSetup->BaudRate = CBR_14400;
374 break;
375 case 19200:
376 comSetup->BaudRate = CBR_19200;
377 break;
378 case 38400:
379 comSetup->BaudRate = CBR_38400;
380 break;
381 case 57600:
382 comSetup->BaudRate = CBR_57600;
383 break;
384 case 115200:
385 comSetup->BaudRate = CBR_115200;
386 break;
387 default:
388 comSetup->BaudRate = CBR_9600;
389 }
390
391 comSetup->fBinary = TRUE;
392 comSetup->fOutxCtsFlow = FALSE;
393 comSetup->fOutxDsrFlow = FALSE;
394 comSetup->fDtrControl = DTR_CONTROL_DISABLE;
395 comSetup->fDsrSensitivity = FALSE;
396 comSetup->fTXContinueOnXoff = TRUE;
397 comSetup->fOutX = FALSE;
398 comSetup->fInX = FALSE;
399 comSetup->fErrorChar = FALSE;
400 comSetup->fNull = FALSE;
401 comSetup->fRtsControl = RTS_CONTROL_DISABLE;
402 comSetup->fAbortOnError = FALSE;
403 comSetup->wReserved = 0;
404 comSetup->XonLim = 5;
405 comSetup->XoffLim = 5;
406 comSetup->ByteSize = cDataBits;
407
408 switch (chParity)
409 {
410 case 'E':
411 comSetup->Parity = EVENPARITY;
412 break;
413 case 'O':
414 comSetup->Parity = ODDPARITY;
415 break;
416 case 'N':
417 comSetup->Parity = NOPARITY;
418 break;
419 default:
420 break;
421 }
422
423 switch (cStopBits)
424 {
425 case 1:
426 comSetup->StopBits = ONESTOPBIT;
427 break;
428 case 2:
429 comSetup->StopBits = TWOSTOPBITS;
430 break;
431 default:
432 break;
433 }
434
435 comSetup->XonChar = 0;
436 comSetup->XoffChar = 0;
437 comSetup->ErrorChar = 0;
438 comSetup->EofChar = 0;
439 comSetup->EvtChar = 0;
440
441 SetCommState(pThis->hDeviceFile, comSetup);
442 RTMemTmpFree(comSetup);
443#endif /* RT_OS_WINDOWS */
444
445 return VINF_SUCCESS;
446}
447
448/* -=-=-=-=- receive thread -=-=-=-=- */
449
450/**
451 * Send thread loop.
452 *
453 * @returns VINF_SUCCESS.
454 * @param ThreadSelf Thread handle to this thread.
455 * @param pvUser User argument.
456 */
457static DECLCALLBACK(int) drvHostSerialSendThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
458{
459 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
460
461 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
462 return VINF_SUCCESS;
463
464#ifdef RT_OS_WINDOWS
465 /* Make sure that the halt event semaphore is reset. */
466 DWORD dwRet = WaitForSingleObject(pThis->hHaltEventSem, 0);
467
468 HANDLE haWait[2];
469 haWait[0] = pThis->hEventSend;
470 haWait[1] = pThis->hHaltEventSem;
471#endif
472
473 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
474 {
475 int rc = RTSemEventWait(pThis->SendSem, RT_INDEFINITE_WAIT);
476 if (RT_FAILURE(rc))
477 break;
478
479 /*
480 * Write the character to the host device.
481 */
482 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
483 {
484 /* copy the send queue so we get a linear buffer with the maximal size. */
485 uint8_t ch = pThis->u8SendByte;
486#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
487
488 size_t cbWritten;
489 rc = RTFileWrite(pThis->hDeviceFile, &ch, 1, &cbWritten);
490 if (rc == VERR_TRY_AGAIN)
491 cbWritten = 0;
492 if (cbWritten < 1 && (RT_SUCCESS(rc) || rc == VERR_TRY_AGAIN))
493 {
494 /* ok, block till the device is ready for more (O_NONBLOCK) effect. */
495 rc = VINF_SUCCESS;
496 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
497 {
498 /* wait */
499 fd_set WrSet;
500 FD_ZERO(&WrSet);
501 FD_SET(RTFileToNative(pThis->hDeviceFile), &WrSet);
502 fd_set XcptSet;
503 FD_ZERO(&XcptSet);
504 FD_SET(RTFileToNative(pThis->hDeviceFile), &XcptSet);
505# ifdef DEBUG
506 uint64_t u64Now = RTTimeMilliTS();
507# endif
508 rc = select(RTFileToNative(pThis->hDeviceFile) + 1, NULL, &WrSet, &XcptSet, NULL);
509 /** @todo check rc? */
510
511# ifdef DEBUG
512 Log2(("select wait for %dms\n", RTTimeMilliTS() - u64Now));
513# endif
514 /* try write more */
515 rc = RTFileWrite(pThis->hDeviceFile, &ch, 1, &cbWritten);
516 if (rc == VERR_TRY_AGAIN)
517 cbWritten = 0;
518 else if (RT_FAILURE(rc))
519 break;
520 else if (cbWritten >= 1)
521 break;
522 rc = VINF_SUCCESS;
523 } /* wait/write loop */
524 }
525
526#elif defined(RT_OS_WINDOWS)
527 /* perform an overlapped write operation. */
528 DWORD cbWritten;
529 memset(&pThis->overlappedSend, 0, sizeof(pThis->overlappedSend));
530 pThis->overlappedSend.hEvent = pThis->hEventSend;
531 if (!WriteFile(pThis->hDeviceFile, &ch, 1, &cbWritten, &pThis->overlappedSend))
532 {
533 dwRet = GetLastError();
534 if (dwRet == ERROR_IO_PENDING)
535 {
536 /*
537 * write blocked, wait for completion or wakeup...
538 */
539 dwRet = WaitForMultipleObjects(2, haWait, FALSE, INFINITE);
540 if (dwRet != WAIT_OBJECT_0)
541 {
542 AssertMsg(pThread->enmState != PDMTHREADSTATE_RUNNING, ("The halt event semaphore is set but the thread is still in running state\n"));
543 break;
544 }
545 }
546 else
547 rc = RTErrConvertFromWin32(dwRet);
548 }
549
550#endif /* RT_OS_WINDOWS */
551 if (RT_FAILURE(rc))
552 {
553 LogRel(("HostSerial#%d: Serial Write failed with %Rrc; terminating send thread\n", pDrvIns->iInstance, rc));
554 return rc;
555 }
556 ASMAtomicXchgBool(&pThis->fSending, false);
557 break;
558 } /* write loop */
559 }
560
561 return VINF_SUCCESS;
562}
563
564/**
565 * Unblock the send thread so it can respond to a state change.
566 *
567 * @returns a VBox status code.
568 * @param pDrvIns The driver instance.
569 * @param pThread The send thread.
570 */
571static DECLCALLBACK(int) drvHostSerialWakeupSendThread(PPDMDRVINS pDrvIns, PPDMTHREAD /*pThread*/)
572{
573 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
574 int rc;
575
576 rc = RTSemEventSignal(pThis->SendSem);
577 if (RT_FAILURE(rc))
578 return rc;
579
580#ifdef RT_OS_WINDOWS
581 if (!SetEvent(pThis->hHaltEventSem))
582 return RTErrConvertFromWin32(GetLastError());
583#endif
584
585 return VINF_SUCCESS;
586}
587
588/* -=-=-=-=- receive thread -=-=-=-=- */
589
590/**
591 * Receive thread loop.
592 *
593 * This thread pushes data from the host serial device up the driver
594 * chain toward the serial device.
595 *
596 * @returns VINF_SUCCESS.
597 * @param ThreadSelf Thread handle to this thread.
598 * @param pvUser User argument.
599 */
600static DECLCALLBACK(int) drvHostSerialRecvThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
601{
602 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
603 uint8_t abBuffer[256];
604 uint8_t *pbBuffer = NULL;
605 size_t cbRemaining = 0; /* start by reading host data */
606 int rc = VINF_SUCCESS;
607 int rcThread = VINF_SUCCESS;
608
609 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
610 return VINF_SUCCESS;
611
612#ifdef RT_OS_WINDOWS
613 /* Make sure that the halt event semaphore is reset. */
614 DWORD dwRet = WaitForSingleObject(pThis->hHaltEventSem, 0);
615
616 HANDLE ahWait[2];
617 ahWait[0] = pThis->hEventRecv;
618 ahWait[1] = pThis->hHaltEventSem;
619#endif
620
621 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
622 {
623 if (!cbRemaining)
624 {
625 /* Get a block of data from the host serial device. */
626
627#if defined(RT_OS_DARWIN) /* poll is broken on x86 darwin, returns POLLNVAL. */
628 fd_set RdSet;
629 FD_ZERO(&RdSet);
630 FD_SET(RTFileToNative(pThis->hDeviceFileR), &RdSet);
631 FD_SET(RTPipeToNative(pThis->hWakeupPipeR), &RdSet);
632 fd_set XcptSet;
633 FD_ZERO(&XcptSet);
634 FD_SET(RTFileToNative(pThis->hDeviceFile), &XcptSet);
635 FD_SET(RTPipeToNative(pThis->hWakeupPipeR), &XcptSet);
636# if 1 /* it seems like this select is blocking the write... */
637 rc = select(RT_MAX(RTPipeToNative(pThis->hWakeupPipeR), RTFileToNative(pThis->hDeviceFileR)) + 1,
638 &RdSet, NULL, &XcptSet, NULL);
639# else
640 struct timeval tv = { 0, 1000 };
641 rc = select(RTPipeToNative(pThis->hWakeupPipeR), RTFileToNative(pThis->hDeviceFileR) + 1,
642 &RdSet, NULL, &XcptSet, &tv);
643# endif
644 if (rc == -1)
645 {
646 int err = errno;
647 rcThread = RTErrConvertFromErrno(err);
648 LogRel(("HostSerial#%d: select failed with errno=%d / %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, err, rcThread));
649 break;
650 }
651
652 /* this might have changed in the meantime */
653 if (pThread->enmState != PDMTHREADSTATE_RUNNING)
654 break;
655 if (rc == 0)
656 continue;
657
658 /* drain the wakeup pipe */
659 size_t cbRead;
660 if ( FD_ISSET(RTPipeToNative(pThis->hWakeupPipeR), &RdSet)
661 || FD_ISSET(RTPipeToNative(pThis->hWakeupPipeR), &XcptSet))
662 {
663 rc = RTPipeRead(pThis->hWakeupPipeR, abBuffer, 1, &cbRead);
664 if (RT_FAILURE(rc))
665 {
666 LogRel(("HostSerial#%d: draining the wakeup pipe failed with %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, rc));
667 rcThread = rc;
668 break;
669 }
670 continue;
671 }
672
673 /* read data from the serial port. */
674 rc = RTFileRead(pThis->hDeviceFileR, abBuffer, sizeof(abBuffer), &cbRead);
675 if (RT_FAILURE(rc))
676 {
677 LogRel(("HostSerial#%d: (1) Read failed with %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, rc));
678 rcThread = rc;
679 break;
680 }
681 cbRemaining = cbRead;
682
683#elif defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
684
685 size_t cbRead;
686 struct pollfd aFDs[2];
687 aFDs[0].fd = RTFileToNative(pThis->hDeviceFile);
688 aFDs[0].events = POLLIN;
689 aFDs[0].revents = 0;
690 aFDs[1].fd = RTPipeToNative(pThis->hWakeupPipeR);
691 aFDs[1].events = POLLIN | POLLERR | POLLHUP;
692 aFDs[1].revents = 0;
693 rc = poll(aFDs, RT_ELEMENTS(aFDs), -1);
694 if (rc < 0)
695 {
696 int err = errno;
697 rcThread = RTErrConvertFromErrno(err);
698 LogRel(("HostSerial#%d: poll failed with errno=%d / %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, err, rcThread));
699 break;
700 }
701 /* this might have changed in the meantime */
702 if (pThread->enmState != PDMTHREADSTATE_RUNNING)
703 break;
704 if (rc > 0 && aFDs[1].revents)
705 {
706 if (aFDs[1].revents & (POLLHUP | POLLERR | POLLNVAL))
707 break;
708 /* notification to terminate -- drain the pipe */
709 RTPipeRead(pThis->hWakeupPipeR, &abBuffer, 1, &cbRead);
710 continue;
711 }
712 rc = RTFileRead(pThis->hDeviceFile, abBuffer, sizeof(abBuffer), &cbRead);
713 if (RT_FAILURE(rc))
714 {
715 /* don't terminate worker thread when data unavailable */
716 if (rc == VERR_TRY_AGAIN)
717 continue;
718
719 LogRel(("HostSerial#%d: (2) Read failed with %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, rc));
720 rcThread = rc;
721 break;
722 }
723 cbRemaining = cbRead;
724
725#elif defined(RT_OS_WINDOWS)
726
727 DWORD dwEventMask = 0;
728 DWORD dwNumberOfBytesTransferred;
729
730 memset(&pThis->overlappedRecv, 0, sizeof(pThis->overlappedRecv));
731 pThis->overlappedRecv.hEvent = pThis->hEventRecv;
732
733 if (!WaitCommEvent(pThis->hDeviceFile, &dwEventMask, &pThis->overlappedRecv))
734 {
735 dwRet = GetLastError();
736 if (dwRet == ERROR_IO_PENDING)
737 {
738 dwRet = WaitForMultipleObjects(2, ahWait, FALSE, INFINITE);
739 if (dwRet != WAIT_OBJECT_0)
740 {
741 /* notification to terminate */
742 AssertMsg(pThread->enmState != PDMTHREADSTATE_RUNNING, ("The halt event semaphore is set but the thread is still in running state\n"));
743 break;
744 }
745 }
746 else
747 {
748 rcThread = RTErrConvertFromWin32(dwRet);
749 LogRel(("HostSerial#%d: Wait failed with error %Rrc; terminating the worker thread.\n", pDrvIns->iInstance, rcThread));
750 break;
751 }
752 }
753 /* this might have changed in the meantime */
754 if (pThread->enmState != PDMTHREADSTATE_RUNNING)
755 break;
756
757 /* Check the event */
758 if (dwEventMask & EV_RXCHAR)
759 {
760 if (!ReadFile(pThis->hDeviceFile, abBuffer, sizeof(abBuffer), &dwNumberOfBytesTransferred, &pThis->overlappedRecv))
761 {
762 rcThread = RTErrConvertFromWin32(GetLastError());
763 LogRel(("HostSerial#%d: Read failed with error %Rrc; terminating the worker thread.\n", pDrvIns->iInstance, rcThread));
764 break;
765 }
766 cbRemaining = dwNumberOfBytesTransferred;
767 }
768 else if (dwEventMask & EV_BREAK)
769 {
770 Log(("HostSerial#%d: Detected break\n"));
771 rc = pThis->pDrvCharPort->pfnNotifyBreak(pThis->pDrvCharPort);
772 }
773 else
774 {
775 /* The status lines have changed. Notify the device. */
776 DWORD dwNewStatusLinesState = 0;
777 uint32_t uNewStatusLinesState = 0;
778
779 /* Get the new state */
780 if (GetCommModemStatus(pThis->hDeviceFile, &dwNewStatusLinesState))
781 {
782 if (dwNewStatusLinesState & MS_RLSD_ON)
783 uNewStatusLinesState |= PDMICHARPORT_STATUS_LINES_DCD;
784 if (dwNewStatusLinesState & MS_RING_ON)
785 uNewStatusLinesState |= PDMICHARPORT_STATUS_LINES_RI;
786 if (dwNewStatusLinesState & MS_DSR_ON)
787 uNewStatusLinesState |= PDMICHARPORT_STATUS_LINES_DSR;
788 if (dwNewStatusLinesState & MS_CTS_ON)
789 uNewStatusLinesState |= PDMICHARPORT_STATUS_LINES_CTS;
790 rc = pThis->pDrvCharPort->pfnNotifyStatusLinesChanged(pThis->pDrvCharPort, uNewStatusLinesState);
791 if (RT_FAILURE(rc))
792 {
793 /* Notifying device failed, continue but log it */
794 LogRel(("HostSerial#%d: Notifying device failed with error %Rrc; continuing.\n", pDrvIns->iInstance, rc));
795 }
796 }
797 else
798 {
799 /* Getting new state failed, continue but log it */
800 LogRel(("HostSerial#%d: Getting status lines state failed with error %Rrc; continuing.\n", pDrvIns->iInstance, RTErrConvertFromWin32(GetLastError())));
801 }
802 }
803#endif
804
805 Log(("Read %d bytes.\n", cbRemaining));
806 pbBuffer = abBuffer;
807 }
808 else
809 {
810 /* Send data to the guest. */
811 size_t cbProcessed = cbRemaining;
812 rc = pThis->pDrvCharPort->pfnNotifyRead(pThis->pDrvCharPort, pbBuffer, &cbProcessed);
813 if (RT_SUCCESS(rc))
814 {
815 Assert(cbProcessed); Assert(cbProcessed <= cbRemaining);
816 pbBuffer += cbProcessed;
817 cbRemaining -= cbProcessed;
818 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbProcessed);
819 }
820 else if (rc == VERR_TIMEOUT)
821 {
822 /* Normal case, just means that the guest didn't accept a new
823 * character before the timeout elapsed. Just retry. */
824 rc = VINF_SUCCESS;
825 }
826 else
827 {
828 LogRel(("HostSerial#%d: NotifyRead failed with %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, rc));
829 rcThread = rc;
830 break;
831 }
832 }
833 }
834
835 return rcThread;
836}
837
838/**
839 * Unblock the send thread so it can respond to a state change.
840 *
841 * @returns a VBox status code.
842 * @param pDrvIns The driver instance.
843 * @param pThread The send thread.
844 */
845static DECLCALLBACK(int) drvHostSerialWakeupRecvThread(PPDMDRVINS pDrvIns, PPDMTHREAD /*pThread*/)
846{
847 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
848#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
849 size_t cbIgnored;
850 return RTPipeWrite(pThis->hWakeupPipeW, "", 1, &cbIgnored);
851
852#elif defined(RT_OS_WINDOWS)
853 if (!SetEvent(pThis->hHaltEventSem))
854 return RTErrConvertFromWin32(GetLastError());
855 return VINF_SUCCESS;
856#else
857# error adapt me!
858#endif
859}
860
861#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
862/* -=-=-=-=- Monitor thread -=-=-=-=- */
863
864/**
865 * Monitor thread loop.
866 *
867 * This thread monitors the status lines and notifies the device
868 * if they change.
869 *
870 * @returns VINF_SUCCESS.
871 * @param ThreadSelf Thread handle to this thread.
872 * @param pvUser User argument.
873 */
874static DECLCALLBACK(int) drvHostSerialMonitorThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
875{
876 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
877 int rc = VINF_SUCCESS;
878 unsigned long const uStatusLinesToCheck = TIOCM_CAR | TIOCM_RNG | TIOCM_DSR | TIOCM_CTS;
879
880 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
881 return VINF_SUCCESS;
882
883 do
884 {
885 unsigned int statusLines;
886
887 /*
888 * Get the status line state.
889 */
890 rc = ioctl(RTFileToNative(pThis->hDeviceFile), TIOCMGET, &statusLines);
891 if (rc < 0)
892 {
893 PDMDrvHlpVMSetRuntimeError(pDrvIns, 0 /*fFlags*/, "DrvHostSerialFail",
894 N_("Ioctl failed for serial host device '%s' (%Rrc). The device will not work properly"),
895 pThis->pszDevicePath, RTErrConvertFromErrno(errno));
896 break;
897 }
898
899 uint32_t newStatusLine = 0;
900
901 if (statusLines & TIOCM_CAR)
902 newStatusLine |= PDMICHARPORT_STATUS_LINES_DCD;
903 if (statusLines & TIOCM_RNG)
904 newStatusLine |= PDMICHARPORT_STATUS_LINES_RI;
905 if (statusLines & TIOCM_DSR)
906 newStatusLine |= PDMICHARPORT_STATUS_LINES_DSR;
907 if (statusLines & TIOCM_CTS)
908 newStatusLine |= PDMICHARPORT_STATUS_LINES_CTS;
909 pThis->pDrvCharPort->pfnNotifyStatusLinesChanged(pThis->pDrvCharPort, newStatusLine);
910
911 if (PDMTHREADSTATE_RUNNING != pThread->enmState)
912 break;
913
914# ifdef RT_OS_LINUX
915 /*
916 * Wait for status line change.
917 *
918 * XXX In Linux, if a thread calls tcsetattr while the monitor thread is
919 * waiting in ioctl for a modem status change then 8250.c wrongly disables
920 * modem irqs and so the monitor thread never gets released. The workaround
921 * is to send a signal after each tcsetattr.
922 */
923 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCMIWAIT, uStatusLinesToCheck);
924# else
925 /* Poll for status line change. */
926 if (!((statusLines ^ pThis->fStatusLines) & uStatusLinesToCheck))
927 PDMR3ThreadSleep(pThread, 500); /* 0.5 sec */
928 pThis->fStatusLines = statusLines;
929# endif
930 }
931 while (PDMTHREADSTATE_RUNNING == pThread->enmState);
932
933 return VINF_SUCCESS;
934}
935
936/**
937 * Unblock the monitor thread so it can respond to a state change.
938 * We need to execute this code exactly once during initialization.
939 * But we don't want to block --- therefore this dedicated thread.
940 *
941 * @returns a VBox status code.
942 * @param pDrvIns The driver instance.
943 * @param pThread The send thread.
944 */
945static DECLCALLBACK(int) drvHostSerialWakeupMonitorThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
946{
947# ifdef RT_OS_LINUX
948 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
949 int rc = VINF_SUCCESS;
950
951 rc = RTThreadPoke(pThread->Thread);
952 if (RT_FAILURE(rc))
953 PDMDrvHlpVMSetRuntimeError(pDrvIns, 0 /*fFlags*/, "DrvHostSerialFail",
954 N_("Suspending serial monitor thread failed for serial device '%s' (%Rrc). The shutdown may take longer than expected"),
955 pThis->pszDevicePath, RTErrConvertFromErrno(rc));
956
957# else /* !RT_OS_LINUX*/
958
959 /* In polling mode there is nobody to wake up (PDMThread will cancel the sleep). */
960 NOREF(pDrvIns);
961 NOREF(pThread);
962
963# endif /* RT_OS_LINUX */
964
965 return VINF_SUCCESS;
966}
967#endif /* RT_OS_LINUX || RT_OS_DARWIN || RT_OS_SOLARIS */
968
969/**
970 * Set the modem lines.
971 *
972 * @returns VBox status code
973 * @param pInterface Pointer to the interface structure.
974 * @param RequestToSend Set to true if this control line should be made active.
975 * @param DataTerminalReady Set to true if this control line should be made active.
976 */
977static DECLCALLBACK(int) drvHostSerialSetModemLines(PPDMICHARCONNECTOR pInterface, bool RequestToSend, bool DataTerminalReady)
978{
979 PDRVHOSTSERIAL pThis = PDMICHAR_2_DRVHOSTSERIAL(pInterface);
980
981#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
982 int modemStateSet = 0;
983 int modemStateClear = 0;
984
985 if (RequestToSend)
986 modemStateSet |= TIOCM_RTS;
987 else
988 modemStateClear |= TIOCM_RTS;
989
990 if (DataTerminalReady)
991 modemStateSet |= TIOCM_DTR;
992 else
993 modemStateClear |= TIOCM_DTR;
994
995 if (modemStateSet)
996 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCMBIS, &modemStateSet);
997
998 if (modemStateClear)
999 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCMBIC, &modemStateClear);
1000
1001#elif defined(RT_OS_WINDOWS)
1002 if (RequestToSend)
1003 EscapeCommFunction(pThis->hDeviceFile, SETRTS);
1004 else
1005 EscapeCommFunction(pThis->hDeviceFile, CLRRTS);
1006
1007 if (DataTerminalReady)
1008 EscapeCommFunction(pThis->hDeviceFile, SETDTR);
1009 else
1010 EscapeCommFunction(pThis->hDeviceFile, CLRDTR);
1011
1012#endif
1013
1014 return VINF_SUCCESS;
1015}
1016
1017/**
1018 * Sets the TD line into break condition.
1019 *
1020 * @returns VBox status code.
1021 * @param pInterface Pointer to the interface structure containing the called function pointer.
1022 * @param fBreak Set to true to let the device send a break false to put into normal operation.
1023 * @thread Any thread.
1024 */
1025static DECLCALLBACK(int) drvHostSerialSetBreak(PPDMICHARCONNECTOR pInterface, bool fBreak)
1026{
1027 PDRVHOSTSERIAL pThis = PDMICHAR_2_DRVHOSTSERIAL(pInterface);
1028
1029#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1030 if (fBreak)
1031 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCSBRK);
1032 else
1033 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCCBRK);
1034
1035#elif defined(RT_OS_WINDOWS)
1036 if (fBreak)
1037 SetCommBreak(pThis->hDeviceFile);
1038 else
1039 ClearCommBreak(pThis->hDeviceFile);
1040#endif
1041
1042 return VINF_SUCCESS;
1043}
1044
1045/* -=-=-=-=- driver interface -=-=-=-=- */
1046
1047/**
1048 * Destruct a char driver instance.
1049 *
1050 * Most VM resources are freed by the VM. This callback is provided so that
1051 * any non-VM resources can be freed correctly.
1052 *
1053 * @param pDrvIns The driver instance data.
1054 */
1055static DECLCALLBACK(void) drvHostSerialDestruct(PPDMDRVINS pDrvIns)
1056{
1057 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
1058 LogFlow(("%s: iInstance=%d\n", __FUNCTION__, pDrvIns->iInstance));
1059 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1060
1061 /* Empty the send queue */
1062 RTSemEventDestroy(pThis->SendSem);
1063 pThis->SendSem = NIL_RTSEMEVENT;
1064
1065 int rc;
1066#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1067
1068 rc = RTPipeClose(pThis->hWakeupPipeW); AssertRC(rc);
1069 pThis->hWakeupPipeW = NIL_RTPIPE;
1070 rc = RTPipeClose(pThis->hWakeupPipeR); AssertRC(rc);
1071 pThis->hWakeupPipeR = NIL_RTPIPE;
1072
1073# if defined(RT_OS_DARWIN)
1074 if (pThis->hDeviceFileR != NIL_RTFILE)
1075 {
1076 if (pThis->hDeviceFileR != pThis->hDeviceFile)
1077 {
1078 rc = RTFileClose(pThis->hDeviceFileR);
1079 AssertRC(rc);
1080 }
1081 pThis->hDeviceFileR = NIL_RTFILE;
1082 }
1083# endif
1084 rc = RTFileClose(pThis->hDeviceFile); AssertRC(rc);
1085 pThis->hDeviceFile = NIL_RTFILE;
1086
1087#elif defined(RT_OS_WINDOWS)
1088 CloseHandle(pThis->hEventRecv);
1089 CloseHandle(pThis->hEventSend);
1090 CancelIo(pThis->hDeviceFile);
1091 CloseHandle(pThis->hDeviceFile);
1092
1093#endif
1094
1095 if (pThis->pszDevicePath)
1096 {
1097 MMR3HeapFree(pThis->pszDevicePath);
1098 pThis->pszDevicePath = NULL;
1099 }
1100}
1101
1102/**
1103 * Construct a char driver instance.
1104 *
1105 * @copydoc FNPDMDRVCONSTRUCT
1106 */
1107static DECLCALLBACK(int) drvHostSerialConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t /*fFlags*/)
1108{
1109 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
1110 LogFlow(("%s: iInstance=%d\n", __FUNCTION__, pDrvIns->iInstance));
1111 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1112
1113 /*
1114 * Init basic data members and interfaces.
1115 */
1116#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1117 pThis->hDeviceFile = NIL_RTFILE;
1118# ifdef RT_OS_DARWIN
1119 pThis->hDeviceFileR = NIL_RTFILE;
1120# endif
1121 pThis->hWakeupPipeR = NIL_RTPIPE;
1122 pThis->hWakeupPipeW = NIL_RTPIPE;
1123#elif defined(RT_OS_WINDOWS)
1124 pThis->hEventRecv = INVALID_HANDLE_VALUE;
1125 pThis->hEventSend = INVALID_HANDLE_VALUE;
1126 pThis->hDeviceFile = INVALID_HANDLE_VALUE;
1127#endif
1128 /* IBase. */
1129 pDrvIns->IBase.pfnQueryInterface = drvHostSerialQueryInterface;
1130 /* ICharConnector. */
1131 pThis->ICharConnector.pfnWrite = drvHostSerialWrite;
1132 pThis->ICharConnector.pfnSetParameters = drvHostSerialSetParameters;
1133 pThis->ICharConnector.pfnSetModemLines = drvHostSerialSetModemLines;
1134 pThis->ICharConnector.pfnSetBreak = drvHostSerialSetBreak;
1135
1136/** @todo Initialize all members with NIL values!! The destructor is ALWAYS called. */
1137
1138 /*
1139 * Query configuration.
1140 */
1141 /* Device */
1142 int rc = CFGMR3QueryStringAlloc(pCfg, "DevicePath", &pThis->pszDevicePath);
1143 if (RT_FAILURE(rc))
1144 {
1145 AssertMsgFailed(("Configuration error: query for \"DevicePath\" string returned %Rra.\n", rc));
1146 return rc;
1147 }
1148
1149 /*
1150 * Open the device
1151 */
1152#ifdef RT_OS_WINDOWS
1153
1154 pThis->hHaltEventSem = CreateEvent(NULL, FALSE, FALSE, NULL);
1155 AssertReturn(pThis->hHaltEventSem != NULL, VERR_NO_MEMORY);
1156
1157 pThis->hEventRecv = CreateEvent(NULL, FALSE, FALSE, NULL);
1158 AssertReturn(pThis->hEventRecv != NULL, VERR_NO_MEMORY);
1159
1160 pThis->hEventSend = CreateEvent(NULL, FALSE, FALSE, NULL);
1161 AssertReturn(pThis->hEventSend != NULL, VERR_NO_MEMORY);
1162
1163 HANDLE hFile = CreateFile(pThis->pszDevicePath,
1164 GENERIC_READ | GENERIC_WRITE,
1165 0, // must be opened with exclusive access
1166 NULL, // no SECURITY_ATTRIBUTES structure
1167 OPEN_EXISTING, // must use OPEN_EXISTING
1168 FILE_FLAG_OVERLAPPED, // overlapped I/O
1169 NULL); // no template file
1170 if (hFile == INVALID_HANDLE_VALUE)
1171 rc = RTErrConvertFromWin32(GetLastError());
1172 else
1173 {
1174 pThis->hDeviceFile = hFile;
1175 /* for overlapped read */
1176 if (!SetCommMask(hFile, EV_RXCHAR | EV_CTS | EV_DSR | EV_RING | EV_RLSD))
1177 {
1178 LogRel(("HostSerial#%d: SetCommMask failed with error %d.\n", pDrvIns->iInstance, GetLastError()));
1179 return VERR_FILE_IO_ERROR;
1180 }
1181 rc = VINF_SUCCESS;
1182 }
1183
1184#else /* !RT_OS_WINDOWS */
1185
1186 uint32_t fOpen = RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE;
1187# ifdef RT_OS_LINUX
1188 /* This seems to be necessary on some Linux hosts, otherwise we hang here forever. */
1189 fOpen |= RTFILE_O_NON_BLOCK;
1190# endif
1191 rc = RTFileOpen(&pThis->hDeviceFile, pThis->pszDevicePath, fOpen);
1192# ifdef RT_OS_LINUX
1193 /* RTFILE_O_NON_BLOCK not supported? */
1194 if (rc == VERR_INVALID_PARAMETER)
1195 rc = RTFileOpen(&pThis->hDeviceFile, pThis->pszDevicePath, fOpen & ~RTFILE_O_NON_BLOCK);
1196# endif
1197# ifdef RT_OS_DARWIN
1198 if (RT_SUCCESS(rc))
1199 rc = RTFileOpen(&pThis->hDeviceFileR, pThis->pszDevicePath, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
1200# endif
1201
1202
1203#endif /* !RT_OS_WINDOWS */
1204
1205 if (RT_FAILURE(rc))
1206 {
1207 AssertMsgFailed(("Could not open host device %s, rc=%Rrc\n", pThis->pszDevicePath, rc));
1208 switch (rc)
1209 {
1210 case VERR_ACCESS_DENIED:
1211 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1212#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1213 N_("Cannot open host device '%s' for read/write access. Check the permissions "
1214 "of that device ('/bin/ls -l %s'): Most probably you need to be member "
1215 "of the device group. Make sure that you logout/login after changing "
1216 "the group settings of the current user"),
1217#else
1218 N_("Cannot open host device '%s' for read/write access. Check the permissions "
1219 "of that device"),
1220#endif
1221 pThis->pszDevicePath, pThis->pszDevicePath);
1222 default:
1223 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1224 N_("Failed to open host device '%s'"),
1225 pThis->pszDevicePath);
1226 }
1227 }
1228
1229 /* Set to non blocking I/O */
1230#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1231
1232 fcntl(RTFileToNative(pThis->hDeviceFile), F_SETFL, O_NONBLOCK);
1233# ifdef RT_OS_DARWIN
1234 fcntl(RTFileToNative(pThis->hDeviceFileR), F_SETFL, O_NONBLOCK);
1235# endif
1236 rc = RTPipeCreate(&pThis->hWakeupPipeR, &pThis->hWakeupPipeW, 0 /*fFlags*/);
1237 AssertRCReturn(rc, rc);
1238
1239#elif defined(RT_OS_WINDOWS)
1240
1241 /* Set the COMMTIMEOUTS to get non blocking I/O */
1242 COMMTIMEOUTS comTimeout;
1243
1244 comTimeout.ReadIntervalTimeout = MAXDWORD;
1245 comTimeout.ReadTotalTimeoutMultiplier = 0;
1246 comTimeout.ReadTotalTimeoutConstant = 0;
1247 comTimeout.WriteTotalTimeoutMultiplier = 0;
1248 comTimeout.WriteTotalTimeoutConstant = 0;
1249
1250 SetCommTimeouts(pThis->hDeviceFile, &comTimeout);
1251
1252#endif
1253
1254 /*
1255 * Get the ICharPort interface of the above driver/device.
1256 */
1257 pThis->pDrvCharPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMICHARPORT);
1258 if (!pThis->pDrvCharPort)
1259 return PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE, RT_SRC_POS, N_("HostSerial#%d has no char port interface above"), pDrvIns->iInstance);
1260
1261 /*
1262 * Create the receive, send and monitor threads plus the related send semaphore.
1263 */
1264 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pRecvThread, pThis, drvHostSerialRecvThread, drvHostSerialWakeupRecvThread, 0, RTTHREADTYPE_IO, "SerRecv");
1265 if (RT_FAILURE(rc))
1266 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("HostSerial#%d cannot create receive thread"), pDrvIns->iInstance);
1267
1268 rc = RTSemEventCreate(&pThis->SendSem);
1269 AssertRC(rc);
1270
1271 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSendThread, pThis, drvHostSerialSendThread, drvHostSerialWakeupSendThread, 0, RTTHREADTYPE_IO, "SerSend");
1272 if (RT_FAILURE(rc))
1273 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("HostSerial#%d cannot create send thread"), pDrvIns->iInstance);
1274
1275#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1276 /* Linux & darwin needs a separate thread which monitors the status lines. */
1277# ifndef RT_OS_LINUX
1278 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCMGET, &pThis->fStatusLines);
1279# endif
1280 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pMonitorThread, pThis, drvHostSerialMonitorThread, drvHostSerialWakeupMonitorThread, 0, RTTHREADTYPE_IO, "SerMon");
1281 if (RT_FAILURE(rc))
1282 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("HostSerial#%d cannot create monitor thread"), pDrvIns->iInstance);
1283#endif
1284
1285 /*
1286 * Register release statistics.
1287 */
1288 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES, "Nr of bytes written", "/Devices/HostSerial%d/Written", pDrvIns->iInstance);
1289 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES, "Nr of bytes read", "/Devices/HostSerial%d/Read", pDrvIns->iInstance);
1290#ifdef RT_OS_DARWIN /* new Write code, not darwin specific. */
1291 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatSendOverflows, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES, "Nr of bytes overflowed", "/Devices/HostSerial%d/SendOverflow", pDrvIns->iInstance);
1292#endif
1293
1294 return VINF_SUCCESS;
1295}
1296
1297/**
1298 * Char driver registration record.
1299 */
1300const PDMDRVREG g_DrvHostSerial =
1301{
1302 /* u32Version */
1303 PDM_DRVREG_VERSION,
1304 /* szName */
1305 "Host Serial",
1306 /* szRCMod */
1307 "",
1308 /* szR0Mod */
1309 "",
1310/* pszDescription */
1311 "Host serial driver.",
1312 /* fFlags */
1313 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1314 /* fClass. */
1315 PDM_DRVREG_CLASS_CHAR,
1316 /* cMaxInstances */
1317 ~0,
1318 /* cbInstance */
1319 sizeof(DRVHOSTSERIAL),
1320 /* pfnConstruct */
1321 drvHostSerialConstruct,
1322 /* pfnDestruct */
1323 drvHostSerialDestruct,
1324 /* pfnRelocate */
1325 NULL,
1326 /* pfnIOCtl */
1327 NULL,
1328 /* pfnPowerOn */
1329 NULL,
1330 /* pfnReset */
1331 NULL,
1332 /* pfnSuspend */
1333 NULL,
1334 /* pfnResume */
1335 NULL,
1336 /* pfnAttach */
1337 NULL,
1338 /* pfnDetach */
1339 NULL,
1340 /* pfnPowerOff */
1341 NULL,
1342 /* pfnSoftReset */
1343 NULL,
1344 /* u32EndVersion */
1345 PDM_DRVREG_VERSION
1346};
1347
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