VirtualBox

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

Last change on this file since 64115 was 63591, checked in by vboxsync, 8 years ago

Serial/Host: Don't try to kick off a thread to monitor the status lines if the device is a pseudo terminal as it doesn't support TIOMCGET

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