VirtualBox

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

最後變更 在這個檔案從33729是 33729,由 vboxsync 提交於 14 年 前

Serial/DevHostSerial: properly handle non-blocking I/O

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

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