VirtualBox

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

Last change on this file since 58466 was 57910, checked in by vboxsync, 9 years ago

DrvHostSerial.cpp: Should call GetOverlappedResult if ReadFile returns ERROR_IO_PENDING. Observed with Free Virtual Serial Ports v3.20.00.0545 on 64-bit Windows 10.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 46.4 KB
Line 
1/* $Id: DrvHostSerial.cpp 57910 2015-09-26 17:24:17Z vboxsync $ */
2/** @file
3 * VBox stream I/O devices: Host serial driver
4 */
5
6/*
7 * Copyright (C) 2006-2015 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 AssertRCBreak(rc);
477
478 /*
479 * Write the character to the host device.
480 */
481 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
482 {
483 /* copy the send queue so we get a linear buffer with the maximal size. */
484 uint8_t ch = pThis->u8SendByte;
485#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
486
487 size_t cbWritten;
488 rc = RTFileWrite(pThis->hDeviceFile, &ch, 1, &cbWritten);
489 if (rc == VERR_TRY_AGAIN)
490 cbWritten = 0;
491 if (cbWritten < 1 && (RT_SUCCESS(rc) || rc == VERR_TRY_AGAIN))
492 {
493 /* ok, block till the device is ready for more (O_NONBLOCK) effect. */
494 rc = VINF_SUCCESS;
495 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
496 {
497 /* wait */
498 fd_set WrSet;
499 FD_ZERO(&WrSet);
500 FD_SET(RTFileToNative(pThis->hDeviceFile), &WrSet);
501 fd_set XcptSet;
502 FD_ZERO(&XcptSet);
503 FD_SET(RTFileToNative(pThis->hDeviceFile), &XcptSet);
504# ifdef DEBUG
505 uint64_t u64Now = RTTimeMilliTS();
506# endif
507 rc = select(RTFileToNative(pThis->hDeviceFile) + 1, NULL, &WrSet, &XcptSet, NULL);
508 /** @todo check rc? */
509
510# ifdef DEBUG
511 Log2(("select wait for %dms\n", RTTimeMilliTS() - u64Now));
512# endif
513 /* try write more */
514 rc = RTFileWrite(pThis->hDeviceFile, &ch, 1, &cbWritten);
515 if (rc == VERR_TRY_AGAIN)
516 cbWritten = 0;
517 else if (RT_FAILURE(rc))
518 break;
519 else if (cbWritten >= 1)
520 break;
521 rc = VINF_SUCCESS;
522 } /* wait/write loop */
523 }
524
525#elif defined(RT_OS_WINDOWS)
526 /* perform an overlapped write operation. */
527 DWORD cbWritten;
528 memset(&pThis->overlappedSend, 0, sizeof(pThis->overlappedSend));
529 pThis->overlappedSend.hEvent = pThis->hEventSend;
530 if (!WriteFile(pThis->hDeviceFile, &ch, 1, &cbWritten, &pThis->overlappedSend))
531 {
532 dwRet = GetLastError();
533 if (dwRet == ERROR_IO_PENDING)
534 {
535 /*
536 * write blocked, wait for completion or wakeup...
537 */
538 dwRet = WaitForMultipleObjects(2, haWait, FALSE, INFINITE);
539 if (dwRet != WAIT_OBJECT_0)
540 {
541 AssertMsg(pThread->enmState != PDMTHREADSTATE_RUNNING, ("The halt event semaphore is set but the thread is still in running state\n"));
542 break;
543 }
544 }
545 else
546 rc = RTErrConvertFromWin32(dwRet);
547 }
548
549#endif /* RT_OS_WINDOWS */
550 if (RT_FAILURE(rc))
551 {
552 LogRel(("HostSerial#%d: Serial Write failed with %Rrc; terminating send thread\n", pDrvIns->iInstance, rc));
553 return rc;
554 }
555 ASMAtomicXchgBool(&pThis->fSending, false);
556 break;
557 } /* write loop */
558 }
559
560 return VINF_SUCCESS;
561}
562
563/**
564 * Unblock the send thread so it can respond to a state change.
565 *
566 * @returns a VBox status code.
567 * @param pDrvIns The driver instance.
568 * @param pThread The send thread.
569 */
570static DECLCALLBACK(int) drvHostSerialWakeupSendThread(PPDMDRVINS pDrvIns, PPDMTHREAD /*pThread*/)
571{
572 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
573 int rc;
574
575 rc = RTSemEventSignal(pThis->SendSem);
576 if (RT_FAILURE(rc))
577 return rc;
578
579#ifdef RT_OS_WINDOWS
580 if (!SetEvent(pThis->hHaltEventSem))
581 return RTErrConvertFromWin32(GetLastError());
582#endif
583
584 return VINF_SUCCESS;
585}
586
587/* -=-=-=-=- receive thread -=-=-=-=- */
588
589/**
590 * Receive thread loop.
591 *
592 * This thread pushes data from the host serial device up the driver
593 * chain toward the serial device.
594 *
595 * @returns VINF_SUCCESS.
596 * @param ThreadSelf Thread handle to this thread.
597 * @param pvUser User argument.
598 */
599static DECLCALLBACK(int) drvHostSerialRecvThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
600{
601 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
602 uint8_t abBuffer[256];
603 uint8_t *pbBuffer = NULL;
604 size_t cbRemaining = 0; /* start by reading host data */
605 int rc = VINF_SUCCESS;
606 int rcThread = VINF_SUCCESS;
607
608 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
609 return VINF_SUCCESS;
610
611#ifdef RT_OS_WINDOWS
612 /* Make sure that the halt event semaphore is reset. */
613 DWORD dwRet = WaitForSingleObject(pThis->hHaltEventSem, 0);
614
615 HANDLE ahWait[2];
616 ahWait[0] = pThis->hEventRecv;
617 ahWait[1] = pThis->hHaltEventSem;
618#endif
619
620 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
621 {
622 if (!cbRemaining)
623 {
624 /* Get a block of data from the host serial device. */
625
626#if defined(RT_OS_DARWIN) /* poll is broken on x86 darwin, returns POLLNVAL. */
627 fd_set RdSet;
628 FD_ZERO(&RdSet);
629 FD_SET(RTFileToNative(pThis->hDeviceFileR), &RdSet);
630 FD_SET(RTPipeToNative(pThis->hWakeupPipeR), &RdSet);
631 fd_set XcptSet;
632 FD_ZERO(&XcptSet);
633 FD_SET(RTFileToNative(pThis->hDeviceFile), &XcptSet);
634 FD_SET(RTPipeToNative(pThis->hWakeupPipeR), &XcptSet);
635# if 1 /* it seems like this select is blocking the write... */
636 rc = select(RT_MAX(RTPipeToNative(pThis->hWakeupPipeR), RTFileToNative(pThis->hDeviceFileR)) + 1,
637 &RdSet, NULL, &XcptSet, NULL);
638# else
639 struct timeval tv = { 0, 1000 };
640 rc = select(RTPipeToNative(pThis->hWakeupPipeR), RTFileToNative(pThis->hDeviceFileR) + 1,
641 &RdSet, NULL, &XcptSet, &tv);
642# endif
643 if (rc == -1)
644 {
645 int err = errno;
646 rcThread = RTErrConvertFromErrno(err);
647 LogRel(("HostSerial#%d: select failed with errno=%d / %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, err, rcThread));
648 break;
649 }
650
651 /* this might have changed in the meantime */
652 if (pThread->enmState != PDMTHREADSTATE_RUNNING)
653 break;
654 if (rc == 0)
655 continue;
656
657 /* drain the wakeup pipe */
658 size_t cbRead;
659 if ( FD_ISSET(RTPipeToNative(pThis->hWakeupPipeR), &RdSet)
660 || FD_ISSET(RTPipeToNative(pThis->hWakeupPipeR), &XcptSet))
661 {
662 rc = RTPipeRead(pThis->hWakeupPipeR, abBuffer, 1, &cbRead);
663 if (RT_FAILURE(rc))
664 {
665 LogRel(("HostSerial#%d: draining the wakeup pipe failed with %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, rc));
666 rcThread = rc;
667 break;
668 }
669 continue;
670 }
671
672 /* read data from the serial port. */
673 rc = RTFileRead(pThis->hDeviceFileR, abBuffer, sizeof(abBuffer), &cbRead);
674 if (RT_FAILURE(rc))
675 {
676 LogRel(("HostSerial#%d: (1) Read failed with %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, rc));
677 rcThread = rc;
678 break;
679 }
680 cbRemaining = cbRead;
681
682#elif defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
683
684 size_t cbRead;
685 struct pollfd aFDs[2];
686 aFDs[0].fd = RTFileToNative(pThis->hDeviceFile);
687 aFDs[0].events = POLLIN;
688 aFDs[0].revents = 0;
689 aFDs[1].fd = RTPipeToNative(pThis->hWakeupPipeR);
690 aFDs[1].events = POLLIN | POLLERR | POLLHUP;
691 aFDs[1].revents = 0;
692 rc = poll(aFDs, RT_ELEMENTS(aFDs), -1);
693 if (rc < 0)
694 {
695 int err = errno;
696 if (err == EINTR)
697 {
698 /*
699 * EINTR errors should be harmless, even if they are not supposed to occur in our setup.
700 */
701 Log(("rc=%d revents=%#x,%#x errno=%p %s\n", rc, aFDs[0].revents, aFDs[1].revents, err, strerror(err)));
702 RTThreadYield();
703 continue;
704 }
705
706 rcThread = RTErrConvertFromErrno(err);
707 LogRel(("HostSerial#%d: poll failed with errno=%d / %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, err, rcThread));
708 break;
709 }
710 /* this might have changed in the meantime */
711 if (pThread->enmState != PDMTHREADSTATE_RUNNING)
712 break;
713 if (rc > 0 && aFDs[1].revents)
714 {
715 if (aFDs[1].revents & (POLLHUP | POLLERR | POLLNVAL))
716 break;
717 /* notification to terminate -- drain the pipe */
718 RTPipeRead(pThis->hWakeupPipeR, &abBuffer, 1, &cbRead);
719 continue;
720 }
721 rc = RTFileRead(pThis->hDeviceFile, abBuffer, sizeof(abBuffer), &cbRead);
722 if (RT_FAILURE(rc))
723 {
724 /* don't terminate worker thread when data unavailable */
725 if (rc == VERR_TRY_AGAIN)
726 continue;
727
728 LogRel(("HostSerial#%d: (2) Read failed with %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, rc));
729 rcThread = rc;
730 break;
731 }
732 cbRemaining = cbRead;
733
734#elif defined(RT_OS_WINDOWS)
735
736 DWORD dwEventMask = 0;
737 DWORD dwNumberOfBytesTransferred;
738
739 memset(&pThis->overlappedRecv, 0, sizeof(pThis->overlappedRecv));
740 pThis->overlappedRecv.hEvent = pThis->hEventRecv;
741
742 if (!WaitCommEvent(pThis->hDeviceFile, &dwEventMask, &pThis->overlappedRecv))
743 {
744 dwRet = GetLastError();
745 if (dwRet == ERROR_IO_PENDING)
746 {
747 dwRet = WaitForMultipleObjects(2, ahWait, FALSE, INFINITE);
748 if (dwRet != WAIT_OBJECT_0)
749 {
750 /* notification to terminate */
751 AssertMsg(pThread->enmState != PDMTHREADSTATE_RUNNING, ("The halt event semaphore is set but the thread is still in running state\n"));
752 break;
753 }
754 }
755 else
756 {
757 rcThread = RTErrConvertFromWin32(dwRet);
758 LogRel(("HostSerial#%d: Wait failed with error %Rrc; terminating the worker thread.\n", pDrvIns->iInstance, rcThread));
759 break;
760 }
761 }
762 /* this might have changed in the meantime */
763 if (pThread->enmState != PDMTHREADSTATE_RUNNING)
764 break;
765
766 /* Check the event */
767 if (dwEventMask & EV_RXCHAR)
768 {
769 if (!ReadFile(pThis->hDeviceFile, abBuffer, sizeof(abBuffer), &dwNumberOfBytesTransferred, &pThis->overlappedRecv))
770 {
771 dwRet = GetLastError();
772 if (dwRet == ERROR_IO_PENDING)
773 {
774 if (GetOverlappedResult(pThis->hDeviceFile, &pThis->overlappedRecv, &dwNumberOfBytesTransferred, TRUE))
775 dwRet = NO_ERROR;
776 else
777 dwRet = GetLastError();
778 }
779 if (dwRet != NO_ERROR)
780 {
781 rcThread = RTErrConvertFromWin32(dwRet);
782 LogRel(("HostSerial#%d: Read failed with error %Rrc; terminating the worker thread.\n", pDrvIns->iInstance, rcThread));
783 break;
784 }
785 }
786 cbRemaining = dwNumberOfBytesTransferred;
787 }
788 else if (dwEventMask & EV_BREAK)
789 {
790 Log(("HostSerial#%d: Detected break\n"));
791 rc = pThis->pDrvCharPort->pfnNotifyBreak(pThis->pDrvCharPort);
792 }
793 else
794 {
795 /* The status lines have changed. Notify the device. */
796 DWORD dwNewStatusLinesState = 0;
797 uint32_t uNewStatusLinesState = 0;
798
799 /* Get the new state */
800 if (GetCommModemStatus(pThis->hDeviceFile, &dwNewStatusLinesState))
801 {
802 if (dwNewStatusLinesState & MS_RLSD_ON)
803 uNewStatusLinesState |= PDMICHARPORT_STATUS_LINES_DCD;
804 if (dwNewStatusLinesState & MS_RING_ON)
805 uNewStatusLinesState |= PDMICHARPORT_STATUS_LINES_RI;
806 if (dwNewStatusLinesState & MS_DSR_ON)
807 uNewStatusLinesState |= PDMICHARPORT_STATUS_LINES_DSR;
808 if (dwNewStatusLinesState & MS_CTS_ON)
809 uNewStatusLinesState |= PDMICHARPORT_STATUS_LINES_CTS;
810 rc = pThis->pDrvCharPort->pfnNotifyStatusLinesChanged(pThis->pDrvCharPort, uNewStatusLinesState);
811 if (RT_FAILURE(rc))
812 {
813 /* Notifying device failed, continue but log it */
814 LogRel(("HostSerial#%d: Notifying device failed with error %Rrc; continuing.\n", pDrvIns->iInstance, rc));
815 }
816 }
817 else
818 {
819 /* Getting new state failed, continue but log it */
820 LogRel(("HostSerial#%d: Getting status lines state failed with error %Rrc; continuing.\n", pDrvIns->iInstance, RTErrConvertFromWin32(GetLastError())));
821 }
822 }
823#endif
824
825 Log(("Read %d bytes.\n", cbRemaining));
826 pbBuffer = abBuffer;
827 }
828 else
829 {
830 /* Send data to the guest. */
831 size_t cbProcessed = cbRemaining;
832 rc = pThis->pDrvCharPort->pfnNotifyRead(pThis->pDrvCharPort, pbBuffer, &cbProcessed);
833 if (RT_SUCCESS(rc))
834 {
835 Assert(cbProcessed); Assert(cbProcessed <= cbRemaining);
836 pbBuffer += cbProcessed;
837 cbRemaining -= cbProcessed;
838 STAM_COUNTER_ADD(&pThis->StatBytesRead, cbProcessed);
839 }
840 else if (rc == VERR_TIMEOUT)
841 {
842 /* Normal case, just means that the guest didn't accept a new
843 * character before the timeout elapsed. Just retry. */
844 rc = VINF_SUCCESS;
845 }
846 else
847 {
848 LogRel(("HostSerial#%d: NotifyRead failed with %Rrc, terminating the worker thread.\n", pDrvIns->iInstance, rc));
849 rcThread = rc;
850 break;
851 }
852 }
853 }
854
855 return rcThread;
856}
857
858/**
859 * Unblock the send thread so it can respond to a state change.
860 *
861 * @returns a VBox status code.
862 * @param pDrvIns The driver instance.
863 * @param pThread The send thread.
864 */
865static DECLCALLBACK(int) drvHostSerialWakeupRecvThread(PPDMDRVINS pDrvIns, PPDMTHREAD /*pThread*/)
866{
867 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
868#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
869 size_t cbIgnored;
870 return RTPipeWrite(pThis->hWakeupPipeW, "", 1, &cbIgnored);
871
872#elif defined(RT_OS_WINDOWS)
873 if (!SetEvent(pThis->hHaltEventSem))
874 return RTErrConvertFromWin32(GetLastError());
875 return VINF_SUCCESS;
876#else
877# error adapt me!
878#endif
879}
880
881#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
882/* -=-=-=-=- Monitor thread -=-=-=-=- */
883
884/**
885 * Monitor thread loop.
886 *
887 * This thread monitors the status lines and notifies the device
888 * if they change.
889 *
890 * @returns VINF_SUCCESS.
891 * @param ThreadSelf Thread handle to this thread.
892 * @param pvUser User argument.
893 */
894static DECLCALLBACK(int) drvHostSerialMonitorThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
895{
896 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
897 int rc = VINF_SUCCESS;
898 unsigned long const uStatusLinesToCheck = TIOCM_CAR | TIOCM_RNG | TIOCM_DSR | TIOCM_CTS;
899
900 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
901 return VINF_SUCCESS;
902
903 do
904 {
905 unsigned int statusLines;
906
907 /*
908 * Get the status line state.
909 */
910 rc = ioctl(RTFileToNative(pThis->hDeviceFile), TIOCMGET, &statusLines);
911 if (rc < 0)
912 {
913 PDMDrvHlpVMSetRuntimeError(pDrvIns, 0 /*fFlags*/, "DrvHostSerialFail",
914 N_("Ioctl failed for serial host device '%s' (%Rrc). The device will not work properly"),
915 pThis->pszDevicePath, RTErrConvertFromErrno(errno));
916 break;
917 }
918
919 uint32_t newStatusLine = 0;
920
921 if (statusLines & TIOCM_CAR)
922 newStatusLine |= PDMICHARPORT_STATUS_LINES_DCD;
923 if (statusLines & TIOCM_RNG)
924 newStatusLine |= PDMICHARPORT_STATUS_LINES_RI;
925 if (statusLines & TIOCM_DSR)
926 newStatusLine |= PDMICHARPORT_STATUS_LINES_DSR;
927 if (statusLines & TIOCM_CTS)
928 newStatusLine |= PDMICHARPORT_STATUS_LINES_CTS;
929 pThis->pDrvCharPort->pfnNotifyStatusLinesChanged(pThis->pDrvCharPort, newStatusLine);
930
931 if (PDMTHREADSTATE_RUNNING != pThread->enmState)
932 break;
933
934# ifdef RT_OS_LINUX
935 /*
936 * Wait for status line change.
937 *
938 * XXX In Linux, if a thread calls tcsetattr while the monitor thread is
939 * waiting in ioctl for a modem status change then 8250.c wrongly disables
940 * modem irqs and so the monitor thread never gets released. The workaround
941 * is to send a signal after each tcsetattr.
942 */
943 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCMIWAIT, uStatusLinesToCheck);
944# else
945 /* Poll for status line change. */
946 if (!((statusLines ^ pThis->fStatusLines) & uStatusLinesToCheck))
947 PDMR3ThreadSleep(pThread, 500); /* 0.5 sec */
948 pThis->fStatusLines = statusLines;
949# endif
950 }
951 while (PDMTHREADSTATE_RUNNING == pThread->enmState);
952
953 return VINF_SUCCESS;
954}
955
956/**
957 * Unblock the monitor thread so it can respond to a state change.
958 * We need to execute this code exactly once during initialization.
959 * But we don't want to block --- therefore this dedicated thread.
960 *
961 * @returns a VBox status code.
962 * @param pDrvIns The driver instance.
963 * @param pThread The send thread.
964 */
965static DECLCALLBACK(int) drvHostSerialWakeupMonitorThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
966{
967# ifdef RT_OS_LINUX
968 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
969 int rc = VINF_SUCCESS;
970
971 rc = RTThreadPoke(pThread->Thread);
972 if (RT_FAILURE(rc))
973 PDMDrvHlpVMSetRuntimeError(pDrvIns, 0 /*fFlags*/, "DrvHostSerialFail",
974 N_("Suspending serial monitor thread failed for serial device '%s' (%Rrc). The shutdown may take longer than expected"),
975 pThis->pszDevicePath, RTErrConvertFromErrno(rc));
976
977# else /* !RT_OS_LINUX*/
978
979 /* In polling mode there is nobody to wake up (PDMThread will cancel the sleep). */
980 NOREF(pDrvIns);
981 NOREF(pThread);
982
983# endif /* RT_OS_LINUX */
984
985 return VINF_SUCCESS;
986}
987#endif /* RT_OS_LINUX || RT_OS_DARWIN || RT_OS_SOLARIS */
988
989/**
990 * Set the modem lines.
991 *
992 * @returns VBox status code
993 * @param pInterface Pointer to the interface structure.
994 * @param RequestToSend Set to true if this control line should be made active.
995 * @param DataTerminalReady Set to true if this control line should be made active.
996 */
997static DECLCALLBACK(int) drvHostSerialSetModemLines(PPDMICHARCONNECTOR pInterface, bool RequestToSend, bool DataTerminalReady)
998{
999 PDRVHOSTSERIAL pThis = PDMICHAR_2_DRVHOSTSERIAL(pInterface);
1000
1001#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1002 int modemStateSet = 0;
1003 int modemStateClear = 0;
1004
1005 if (RequestToSend)
1006 modemStateSet |= TIOCM_RTS;
1007 else
1008 modemStateClear |= TIOCM_RTS;
1009
1010 if (DataTerminalReady)
1011 modemStateSet |= TIOCM_DTR;
1012 else
1013 modemStateClear |= TIOCM_DTR;
1014
1015 if (modemStateSet)
1016 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCMBIS, &modemStateSet);
1017
1018 if (modemStateClear)
1019 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCMBIC, &modemStateClear);
1020
1021#elif defined(RT_OS_WINDOWS)
1022 if (RequestToSend)
1023 EscapeCommFunction(pThis->hDeviceFile, SETRTS);
1024 else
1025 EscapeCommFunction(pThis->hDeviceFile, CLRRTS);
1026
1027 if (DataTerminalReady)
1028 EscapeCommFunction(pThis->hDeviceFile, SETDTR);
1029 else
1030 EscapeCommFunction(pThis->hDeviceFile, CLRDTR);
1031
1032#endif
1033
1034 return VINF_SUCCESS;
1035}
1036
1037/**
1038 * Sets the TD line into break condition.
1039 *
1040 * @returns VBox status code.
1041 * @param pInterface Pointer to the interface structure containing the called function pointer.
1042 * @param fBreak Set to true to let the device send a break false to put into normal operation.
1043 * @thread Any thread.
1044 */
1045static DECLCALLBACK(int) drvHostSerialSetBreak(PPDMICHARCONNECTOR pInterface, bool fBreak)
1046{
1047 PDRVHOSTSERIAL pThis = PDMICHAR_2_DRVHOSTSERIAL(pInterface);
1048
1049#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1050 if (fBreak)
1051 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCSBRK);
1052 else
1053 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCCBRK);
1054
1055#elif defined(RT_OS_WINDOWS)
1056 if (fBreak)
1057 SetCommBreak(pThis->hDeviceFile);
1058 else
1059 ClearCommBreak(pThis->hDeviceFile);
1060#endif
1061
1062 return VINF_SUCCESS;
1063}
1064
1065/* -=-=-=-=- driver interface -=-=-=-=- */
1066
1067/**
1068 * Destruct a char driver instance.
1069 *
1070 * Most VM resources are freed by the VM. This callback is provided so that
1071 * any non-VM resources can be freed correctly.
1072 *
1073 * @param pDrvIns The driver instance data.
1074 */
1075static DECLCALLBACK(void) drvHostSerialDestruct(PPDMDRVINS pDrvIns)
1076{
1077 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
1078 LogFlow(("%s: iInstance=%d\n", __FUNCTION__, pDrvIns->iInstance));
1079 PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);
1080
1081 /* Empty the send queue */
1082 if (pThis->SendSem != NIL_RTSEMEVENT)
1083 {
1084 RTSemEventDestroy(pThis->SendSem);
1085 pThis->SendSem = NIL_RTSEMEVENT;
1086 }
1087
1088#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1089
1090 int rc = RTPipeClose(pThis->hWakeupPipeW); AssertRC(rc);
1091 pThis->hWakeupPipeW = NIL_RTPIPE;
1092 rc = RTPipeClose(pThis->hWakeupPipeR); AssertRC(rc);
1093 pThis->hWakeupPipeR = NIL_RTPIPE;
1094
1095# if defined(RT_OS_DARWIN)
1096 if (pThis->hDeviceFileR != NIL_RTFILE)
1097 {
1098 if (pThis->hDeviceFileR != pThis->hDeviceFile)
1099 {
1100 rc = RTFileClose(pThis->hDeviceFileR);
1101 AssertRC(rc);
1102 }
1103 pThis->hDeviceFileR = NIL_RTFILE;
1104 }
1105# endif
1106 if (pThis->hDeviceFile != NIL_RTFILE)
1107 {
1108 rc = RTFileClose(pThis->hDeviceFile); AssertRC(rc);
1109 pThis->hDeviceFile = NIL_RTFILE;
1110 }
1111
1112#elif defined(RT_OS_WINDOWS)
1113 CloseHandle(pThis->hEventRecv);
1114 CloseHandle(pThis->hEventSend);
1115 CancelIo(pThis->hDeviceFile);
1116 CloseHandle(pThis->hDeviceFile);
1117
1118#endif
1119
1120 if (pThis->pszDevicePath)
1121 {
1122 MMR3HeapFree(pThis->pszDevicePath);
1123 pThis->pszDevicePath = NULL;
1124 }
1125}
1126
1127/**
1128 * Construct a char driver instance.
1129 *
1130 * @copydoc FNPDMDRVCONSTRUCT
1131 */
1132static DECLCALLBACK(int) drvHostSerialConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t /*fFlags*/)
1133{
1134 PDRVHOSTSERIAL pThis = PDMINS_2_DATA(pDrvIns, PDRVHOSTSERIAL);
1135 LogFlow(("%s: iInstance=%d\n", __FUNCTION__, pDrvIns->iInstance));
1136 PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
1137
1138 /*
1139 * Init basic data members and interfaces.
1140 */
1141#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1142 pThis->hDeviceFile = NIL_RTFILE;
1143# ifdef RT_OS_DARWIN
1144 pThis->hDeviceFileR = NIL_RTFILE;
1145# endif
1146 pThis->hWakeupPipeR = NIL_RTPIPE;
1147 pThis->hWakeupPipeW = NIL_RTPIPE;
1148#elif defined(RT_OS_WINDOWS)
1149 pThis->hEventRecv = INVALID_HANDLE_VALUE;
1150 pThis->hEventSend = INVALID_HANDLE_VALUE;
1151 pThis->hDeviceFile = INVALID_HANDLE_VALUE;
1152#endif
1153 pThis->SendSem = NIL_RTSEMEVENT;
1154 /* IBase. */
1155 pDrvIns->IBase.pfnQueryInterface = drvHostSerialQueryInterface;
1156 /* ICharConnector. */
1157 pThis->ICharConnector.pfnWrite = drvHostSerialWrite;
1158 pThis->ICharConnector.pfnSetParameters = drvHostSerialSetParameters;
1159 pThis->ICharConnector.pfnSetModemLines = drvHostSerialSetModemLines;
1160 pThis->ICharConnector.pfnSetBreak = drvHostSerialSetBreak;
1161
1162 /*
1163 * Query configuration.
1164 */
1165 /* Device */
1166 int rc = CFGMR3QueryStringAlloc(pCfg, "DevicePath", &pThis->pszDevicePath);
1167 if (RT_FAILURE(rc))
1168 {
1169 AssertMsgFailed(("Configuration error: query for \"DevicePath\" string returned %Rra.\n", rc));
1170 return rc;
1171 }
1172
1173 /*
1174 * Open the device
1175 */
1176#ifdef RT_OS_WINDOWS
1177
1178 pThis->hHaltEventSem = CreateEvent(NULL, FALSE, FALSE, NULL);
1179 AssertReturn(pThis->hHaltEventSem != NULL, VERR_NO_MEMORY);
1180
1181 pThis->hEventRecv = CreateEvent(NULL, FALSE, FALSE, NULL);
1182 AssertReturn(pThis->hEventRecv != NULL, VERR_NO_MEMORY);
1183
1184 pThis->hEventSend = CreateEvent(NULL, FALSE, FALSE, NULL);
1185 AssertReturn(pThis->hEventSend != NULL, VERR_NO_MEMORY);
1186
1187 HANDLE hFile = CreateFile(pThis->pszDevicePath,
1188 GENERIC_READ | GENERIC_WRITE,
1189 0, // must be opened with exclusive access
1190 NULL, // no SECURITY_ATTRIBUTES structure
1191 OPEN_EXISTING, // must use OPEN_EXISTING
1192 FILE_FLAG_OVERLAPPED, // overlapped I/O
1193 NULL); // no template file
1194 if (hFile == INVALID_HANDLE_VALUE)
1195 rc = RTErrConvertFromWin32(GetLastError());
1196 else
1197 {
1198 pThis->hDeviceFile = hFile;
1199 /* for overlapped read */
1200 if (!SetCommMask(hFile, EV_RXCHAR | EV_CTS | EV_DSR | EV_RING | EV_RLSD))
1201 {
1202 LogRel(("HostSerial#%d: SetCommMask failed with error %d.\n", pDrvIns->iInstance, GetLastError()));
1203 return VERR_FILE_IO_ERROR;
1204 }
1205 rc = VINF_SUCCESS;
1206 }
1207
1208#else /* !RT_OS_WINDOWS */
1209
1210 uint32_t fOpen = RTFILE_O_READWRITE | RTFILE_O_OPEN | RTFILE_O_DENY_NONE;
1211# ifdef RT_OS_LINUX
1212 /* This seems to be necessary on some Linux hosts, otherwise we hang here forever. */
1213 fOpen |= RTFILE_O_NON_BLOCK;
1214# endif
1215 rc = RTFileOpen(&pThis->hDeviceFile, pThis->pszDevicePath, fOpen);
1216# ifdef RT_OS_LINUX
1217 /* RTFILE_O_NON_BLOCK not supported? */
1218 if (rc == VERR_INVALID_PARAMETER)
1219 rc = RTFileOpen(&pThis->hDeviceFile, pThis->pszDevicePath, fOpen & ~RTFILE_O_NON_BLOCK);
1220# endif
1221# ifdef RT_OS_DARWIN
1222 if (RT_SUCCESS(rc))
1223 rc = RTFileOpen(&pThis->hDeviceFileR, pThis->pszDevicePath, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
1224# endif
1225
1226
1227#endif /* !RT_OS_WINDOWS */
1228
1229 if (RT_FAILURE(rc))
1230 {
1231 AssertMsgFailed(("Could not open host device %s, rc=%Rrc\n", pThis->pszDevicePath, rc));
1232 switch (rc)
1233 {
1234 case VERR_ACCESS_DENIED:
1235 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1236#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1237 N_("Cannot open host device '%s' for read/write access. Check the permissions "
1238 "of that device ('/bin/ls -l %s'): Most probably you need to be member "
1239 "of the device group. Make sure that you logout/login after changing "
1240 "the group settings of the current user"),
1241#else
1242 N_("Cannot open host device '%s' for read/write access. Check the permissions "
1243 "of that device"),
1244#endif
1245 pThis->pszDevicePath, pThis->pszDevicePath);
1246 default:
1247 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
1248 N_("Failed to open host device '%s'"),
1249 pThis->pszDevicePath);
1250 }
1251 }
1252
1253 /* Set to non blocking I/O */
1254#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1255
1256 fcntl(RTFileToNative(pThis->hDeviceFile), F_SETFL, O_NONBLOCK);
1257# ifdef RT_OS_DARWIN
1258 fcntl(RTFileToNative(pThis->hDeviceFileR), F_SETFL, O_NONBLOCK);
1259# endif
1260 rc = RTPipeCreate(&pThis->hWakeupPipeR, &pThis->hWakeupPipeW, 0 /*fFlags*/);
1261 AssertRCReturn(rc, rc);
1262
1263#elif defined(RT_OS_WINDOWS)
1264
1265 /* Set the COMMTIMEOUTS to get non blocking I/O */
1266 COMMTIMEOUTS comTimeout;
1267
1268 comTimeout.ReadIntervalTimeout = MAXDWORD;
1269 comTimeout.ReadTotalTimeoutMultiplier = 0;
1270 comTimeout.ReadTotalTimeoutConstant = 0;
1271 comTimeout.WriteTotalTimeoutMultiplier = 0;
1272 comTimeout.WriteTotalTimeoutConstant = 0;
1273
1274 SetCommTimeouts(pThis->hDeviceFile, &comTimeout);
1275
1276#endif
1277
1278 /*
1279 * Get the ICharPort interface of the above driver/device.
1280 */
1281 pThis->pDrvCharPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMICHARPORT);
1282 if (!pThis->pDrvCharPort)
1283 return PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE, RT_SRC_POS, N_("HostSerial#%d has no char port interface above"), pDrvIns->iInstance);
1284
1285 /*
1286 * Create the receive, send and monitor threads plus the related send semaphore.
1287 */
1288 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pRecvThread, pThis, drvHostSerialRecvThread, drvHostSerialWakeupRecvThread, 0, RTTHREADTYPE_IO, "SerRecv");
1289 if (RT_FAILURE(rc))
1290 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("HostSerial#%d cannot create receive thread"), pDrvIns->iInstance);
1291
1292 rc = RTSemEventCreate(&pThis->SendSem);
1293 AssertRC(rc);
1294
1295 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pSendThread, pThis, drvHostSerialSendThread, drvHostSerialWakeupSendThread, 0, RTTHREADTYPE_IO, "SerSend");
1296 if (RT_FAILURE(rc))
1297 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("HostSerial#%d cannot create send thread"), pDrvIns->iInstance);
1298
1299#if defined(RT_OS_LINUX) || defined(RT_OS_DARWIN) || defined(RT_OS_SOLARIS) || defined(RT_OS_FREEBSD)
1300 /* Linux & darwin needs a separate thread which monitors the status lines. */
1301# ifndef RT_OS_LINUX
1302 ioctl(RTFileToNative(pThis->hDeviceFile), TIOCMGET, &pThis->fStatusLines);
1303# endif
1304 rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pMonitorThread, pThis, drvHostSerialMonitorThread, drvHostSerialWakeupMonitorThread, 0, RTTHREADTYPE_IO, "SerMon");
1305 if (RT_FAILURE(rc))
1306 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("HostSerial#%d cannot create monitor thread"), pDrvIns->iInstance);
1307#endif
1308
1309 /*
1310 * Register release statistics.
1311 */
1312 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatBytesWritten, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES, "Nr of bytes written", "/Devices/HostSerial%d/Written", pDrvIns->iInstance);
1313 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatBytesRead, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES, "Nr of bytes read", "/Devices/HostSerial%d/Read", pDrvIns->iInstance);
1314#ifdef RT_OS_DARWIN /* new Write code, not darwin specific. */
1315 PDMDrvHlpSTAMRegisterF(pDrvIns, &pThis->StatSendOverflows, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES, "Nr of bytes overflowed", "/Devices/HostSerial%d/SendOverflow", pDrvIns->iInstance);
1316#endif
1317
1318 return VINF_SUCCESS;
1319}
1320
1321/**
1322 * Char driver registration record.
1323 */
1324const PDMDRVREG g_DrvHostSerial =
1325{
1326 /* u32Version */
1327 PDM_DRVREG_VERSION,
1328 /* szName */
1329 "Host Serial",
1330 /* szRCMod */
1331 "",
1332 /* szR0Mod */
1333 "",
1334/* pszDescription */
1335 "Host serial driver.",
1336 /* fFlags */
1337 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1338 /* fClass. */
1339 PDM_DRVREG_CLASS_CHAR,
1340 /* cMaxInstances */
1341 ~0U,
1342 /* cbInstance */
1343 sizeof(DRVHOSTSERIAL),
1344 /* pfnConstruct */
1345 drvHostSerialConstruct,
1346 /* pfnDestruct */
1347 drvHostSerialDestruct,
1348 /* pfnRelocate */
1349 NULL,
1350 /* pfnIOCtl */
1351 NULL,
1352 /* pfnPowerOn */
1353 NULL,
1354 /* pfnReset */
1355 NULL,
1356 /* pfnSuspend */
1357 NULL,
1358 /* pfnResume */
1359 NULL,
1360 /* pfnAttach */
1361 NULL,
1362 /* pfnDetach */
1363 NULL,
1364 /* pfnPowerOff */
1365 NULL,
1366 /* pfnSoftReset */
1367 NULL,
1368 /* u32EndVersion */
1369 PDM_DRVREG_VERSION
1370};
1371
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