VirtualBox

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

Last change on this file since 6071 was 6016, checked in by vboxsync, 17 years ago

First try to implement monitoring of status lines

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 32.0 KB
Line 
1/** $Id: DrvHostSerial.cpp 6016 2007-12-09 00:19:24Z vboxsync $ */
2/** @file
3 * VBox stream I/O devices: Host serial driver
4 *
5 * Contributed by: Alexander Eichner
6 */
7
8/*
9 * Copyright (C) 2006-2007 innotek GmbH
10 *
11 * This file is part of VirtualBox Open Source Edition (OSE), as
12 * available from http://www.virtualbox.org. This file is free software;
13 * you can redistribute it and/or modify it under the terms of the GNU
14 * General Public License (GPL) as published by the Free Software
15 * Foundation, in version 2 as it comes in the "COPYING" file of the
16 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
17 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
18 */
19
20
21
22/*******************************************************************************
23* Header Files *
24*******************************************************************************/
25#define LOG_GROUP LOG_GROUP_DRV_HOST_SERIAL
26#include <VBox/pdm.h>
27#include <VBox/err.h>
28
29#include <VBox/log.h>
30#include <iprt/asm.h>
31#include <iprt/assert.h>
32#include <iprt/stream.h>
33#include <iprt/semaphore.h>
34#include <iprt/file.h>
35#include <iprt/alloc.h>
36
37#ifdef RT_OS_LINUX
38# include <errno.h>
39# include <termios.h>
40# include <sys/types.h>
41# include <fcntl.h>
42# include <string.h>
43# include <unistd.h>
44# include <sys/poll.h>
45# include <sys/ioctl.h>
46
47/*
48 * TIOCM_LOOP is not defined in the above header files for some reason but in asm/termios.h.
49 * But inclusion of this file however leads to compilation errors because of redefinition of some
50 * structs. Thatswhy it is defined here until a better solution is found.
51 */
52#ifndef TIOCM_LOOP
53# define TIOCM_LOOP 0x8000
54#endif
55
56#elif defined(RT_OS_WINDOWS)
57# include <windows.h>
58#endif
59
60#include "Builtins.h"
61
62
63/** Size of the send fifo queue (in bytes) */
64#define CHAR_MAX_SEND_QUEUE 0x80
65#define CHAR_MAX_SEND_QUEUE_MASK 0x7f
66
67/*******************************************************************************
68* Structures and Typedefs *
69*******************************************************************************/
70
71/**
72 * Char driver instance data.
73 */
74typedef struct DRVHOSTSERIAL
75{
76 /** Pointer to the driver instance structure. */
77 PPDMDRVINS pDrvIns;
78 /** Pointer to the char port interface of the driver/device above us. */
79 PPDMICHARPORT pDrvCharPort;
80 /** Our char interface. */
81 PDMICHAR IChar;
82 /** Receive thread. */
83 PPDMTHREAD pRecvThread;
84 /** Send thread. */
85 PPDMTHREAD pSendThread;
86 /** Status lines monitor thread. */
87 PPDMTHREAD pMonitorThread;
88 /** Send event semephore */
89 RTSEMEVENT SendSem;
90
91 /** the device path */
92 char *pszDevicePath;
93
94#ifdef RT_OS_LINUX
95 /** the device handle */
96 RTFILE DeviceFile;
97 /** The read end of the control pipe */
98 RTFILE WakeupPipeR;
99 /** The write end of the control pipe */
100 RTFILE WakeupPipeW;
101#elif defined(RT_OS_WINDOWS)
102 /** the device handle */
103 HANDLE hDeviceFile;
104 /** The event semaphore for waking up the receive thread */
105 HANDLE hHaltEventSem;
106 /** The event semaphore for overlapped receiving */
107 HANDLE hEventRecv;
108 /** For overlapped receiving */
109 OVERLAPPED overlappedRecv;
110 /** The event semaphore for overlapped sending */
111 HANDLE hEventSend;
112 /** For overlapped sending */
113 OVERLAPPED overlappedSend;
114#endif
115
116 /** Internal send FIFO queue */
117 uint8_t aSendQueue[CHAR_MAX_SEND_QUEUE];
118 uint32_t iSendQueueHead;
119 uint32_t iSendQueueTail;
120
121 /** Read/write statistics */
122 STAMCOUNTER StatBytesRead;
123 STAMCOUNTER StatBytesWritten;
124} DRVHOSTSERIAL, *PDRVHOSTSERIAL;
125
126
127/** Converts a pointer to DRVCHAR::IChar to a PDRVHOSTSERIAL. */
128#define PDMICHAR_2_DRVHOSTSERIAL(pInterface) ( (PDRVHOSTSERIAL)((uintptr_t)pInterface - RT_OFFSETOF(DRVHOSTSERIAL, IChar)) )
129
130
131/* -=-=-=-=- IBase -=-=-=-=- */
132
133/**
134 * Queries an interface to the driver.
135 *
136 * @returns Pointer to interface.
137 * @returns NULL if the interface was not supported by the driver.
138 * @param pInterface Pointer to this interface structure.
139 * @param enmInterface The requested interface identification.
140 */
141static DECLCALLBACK(void *) drvHostSerialQueryInterface(PPDMIBASE pInterface, PDMINTERFACE enmInterface)
142{
143 PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
144 PDRVHOSTSERIAL pData = PDMINS2DATA(pDrvIns, PDRVHOSTSERIAL);
145 switch (enmInterface)
146 {
147 case PDMINTERFACE_BASE:
148 return &pDrvIns->IBase;
149 case PDMINTERFACE_CHAR:
150 return &pData->IChar;
151 default:
152 return NULL;
153 }
154}
155
156
157/* -=-=-=-=- IChar -=-=-=-=- */
158
159/** @copydoc PDMICHAR::pfnWrite */
160static DECLCALLBACK(int) drvHostSerialWrite(PPDMICHAR pInterface, const void *pvBuf, size_t cbWrite)
161{
162 PDRVHOSTSERIAL pData = PDMICHAR_2_DRVHOSTSERIAL(pInterface);
163 const uint8_t *pbBuffer = (const uint8_t *)pvBuf;
164
165 LogFlow(("%s: pvBuf=%#p cbWrite=%d\n", __FUNCTION__, pvBuf, cbWrite));
166
167 for (uint32_t i=0;i<cbWrite;i++)
168 {
169 uint32_t idx = pData->iSendQueueHead;
170
171 pData->aSendQueue[idx] = pbBuffer[i];
172 idx = (idx + 1) & CHAR_MAX_SEND_QUEUE_MASK;
173
174 STAM_COUNTER_INC(&pData->StatBytesWritten);
175 ASMAtomicXchgU32(&pData->iSendQueueHead, idx);
176 }
177 RTSemEventSignal(pData->SendSem);
178 return VINF_SUCCESS;
179}
180
181static DECLCALLBACK(int) drvHostSerialSetParameters(PPDMICHAR pInterface, unsigned Bps, char chParity, unsigned cDataBits, unsigned cStopBits)
182{
183 PDRVHOSTSERIAL pData = PDMICHAR_2_DRVHOSTSERIAL(pInterface);
184#ifdef RT_OS_LINUX
185 struct termios *termiosSetup;
186 int baud_rate;
187#elif defined(RT_OS_WINDOWS)
188 LPDCB comSetup;
189#endif
190
191 LogFlow(("%s: Bps=%u chParity=%c cDataBits=%u cStopBits=%u\n", __FUNCTION__, Bps, chParity, cDataBits, cStopBits));
192
193#ifdef RT_OS_LINUX
194 termiosSetup = (struct termios *)RTMemTmpAllocZ(sizeof(struct termios));
195
196 /* Enable receiver */
197 termiosSetup->c_cflag |= (CLOCAL | CREAD);
198
199 switch (Bps) {
200 case 50:
201 baud_rate = B50;
202 break;
203 case 75:
204 baud_rate = B75;
205 break;
206 case 110:
207 baud_rate = B110;
208 break;
209 case 134:
210 baud_rate = B134;
211 break;
212 case 150:
213 baud_rate = B150;
214 break;
215 case 200:
216 baud_rate = B200;
217 break;
218 case 300:
219 baud_rate = B300;
220 break;
221 case 600:
222 baud_rate = B600;
223 break;
224 case 1200:
225 baud_rate = B1200;
226 break;
227 case 1800:
228 baud_rate = B1800;
229 break;
230 case 2400:
231 baud_rate = B2400;
232 break;
233 case 4800:
234 baud_rate = B4800;
235 break;
236 case 9600:
237 baud_rate = B9600;
238 break;
239 case 19200:
240 baud_rate = B19200;
241 break;
242 case 38400:
243 baud_rate = B38400;
244 break;
245 case 57600:
246 baud_rate = B57600;
247 break;
248 case 115200:
249 baud_rate = B115200;
250 break;
251 default:
252 baud_rate = B9600;
253 }
254
255 cfsetispeed(termiosSetup, baud_rate);
256 cfsetospeed(termiosSetup, baud_rate);
257
258 switch (chParity) {
259 case 'E':
260 termiosSetup->c_cflag |= PARENB;
261 break;
262 case 'O':
263 termiosSetup->c_cflag |= (PARENB | PARODD);
264 break;
265 case 'N':
266 break;
267 default:
268 break;
269 }
270
271 switch (cDataBits) {
272 case 5:
273 termiosSetup->c_cflag |= CS5;
274 break;
275 case 6:
276 termiosSetup->c_cflag |= CS6;
277 break;
278 case 7:
279 termiosSetup->c_cflag |= CS7;
280 break;
281 case 8:
282 termiosSetup->c_cflag |= CS8;
283 break;
284 default:
285 break;
286 }
287
288 switch (cStopBits) {
289 case 2:
290 termiosSetup->c_cflag |= CSTOPB;
291 default:
292 break;
293 }
294
295 /* set serial port to raw input */
296 termiosSetup->c_lflag = ~(ICANON | ECHO | ECHOE | ISIG);
297
298 tcsetattr(pData->DeviceFile, TCSANOW, termiosSetup);
299 RTMemTmpFree(termiosSetup);
300#elif defined(RT_OS_WINDOWS)
301 comSetup = (LPDCB)RTMemTmpAllocZ(sizeof(DCB));
302
303 comSetup->DCBlength = sizeof(DCB);
304
305 switch (Bps) {
306 case 110:
307 comSetup->BaudRate = CBR_110;
308 break;
309 case 300:
310 comSetup->BaudRate = CBR_300;
311 break;
312 case 600:
313 comSetup->BaudRate = CBR_600;
314 break;
315 case 1200:
316 comSetup->BaudRate = CBR_1200;
317 break;
318 case 2400:
319 comSetup->BaudRate = CBR_2400;
320 break;
321 case 4800:
322 comSetup->BaudRate = CBR_4800;
323 break;
324 case 9600:
325 comSetup->BaudRate = CBR_9600;
326 break;
327 case 14400:
328 comSetup->BaudRate = CBR_14400;
329 break;
330 case 19200:
331 comSetup->BaudRate = CBR_19200;
332 break;
333 case 38400:
334 comSetup->BaudRate = CBR_38400;
335 break;
336 case 57600:
337 comSetup->BaudRate = CBR_57600;
338 break;
339 case 115200:
340 comSetup->BaudRate = CBR_115200;
341 break;
342 default:
343 comSetup->BaudRate = CBR_9600;
344 }
345
346 comSetup->fBinary = TRUE;
347 comSetup->fOutxCtsFlow = FALSE;
348 comSetup->fOutxDsrFlow = FALSE;
349 comSetup->fDtrControl = DTR_CONTROL_DISABLE;
350 comSetup->fDsrSensitivity = FALSE;
351 comSetup->fTXContinueOnXoff = TRUE;
352 comSetup->fOutX = FALSE;
353 comSetup->fInX = FALSE;
354 comSetup->fErrorChar = FALSE;
355 comSetup->fNull = FALSE;
356 comSetup->fRtsControl = RTS_CONTROL_DISABLE;
357 comSetup->fAbortOnError = FALSE;
358 comSetup->wReserved = 0;
359 comSetup->XonLim = 5;
360 comSetup->XoffLim = 5;
361 comSetup->ByteSize = cDataBits;
362
363 switch (chParity) {
364 case 'E':
365 comSetup->Parity = EVENPARITY;
366 break;
367 case 'O':
368 comSetup->Parity = ODDPARITY;
369 break;
370 case 'N':
371 comSetup->Parity = NOPARITY;
372 break;
373 default:
374 break;
375 }
376
377 switch (cStopBits) {
378 case 1:
379 comSetup->StopBits = ONESTOPBIT;
380 break;
381 case 2:
382 comSetup->StopBits = TWOSTOPBITS;
383 break;
384 default:
385 break;
386 }
387
388 comSetup->XonChar = 0;
389 comSetup->XoffChar = 0;
390 comSetup->ErrorChar = 0;
391 comSetup->EofChar = 0;
392 comSetup->EvtChar = 0;
393
394 SetCommState(pData->hDeviceFile, comSetup);
395 RTMemTmpFree(comSetup);
396#endif /* RT_OS_WINDOWS */
397
398 return VINF_SUCCESS;
399}
400
401/* -=-=-=-=- receive thread -=-=-=-=- */
402
403/**
404 * Send thread loop.
405 *
406 * @returns VINF_SUCCESS.
407 * @param ThreadSelf Thread handle to this thread.
408 * @param pvUser User argument.
409 */
410static DECLCALLBACK(int) drvHostSerialSendThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
411{
412 PDRVHOSTSERIAL pData = PDMINS2DATA(pDrvIns, PDRVHOSTSERIAL);
413
414 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
415 return VINF_SUCCESS;
416
417#ifdef RT_OS_WINDOWS
418 HANDLE haWait[2];
419 haWait[0] = pData->hEventSend;
420 haWait[1] = pData->hHaltEventSem;
421#endif
422
423 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
424 {
425 int rc = RTSemEventWait(pData->SendSem, RT_INDEFINITE_WAIT);
426 if (VBOX_FAILURE(rc))
427 break;
428
429 /*
430 * Write the character to the host device.
431 */
432 while ( pThread->enmState == PDMTHREADSTATE_RUNNING
433 && pData->iSendQueueTail != pData->iSendQueueHead)
434 {
435 unsigned cbProcessed = 1;
436
437#if defined(RT_OS_LINUX)
438
439 rc = RTFileWrite(pData->DeviceFile, &pData->aSendQueue[pData->iSendQueueTail], cbProcessed, NULL);
440
441#elif defined(RT_OS_WINDOWS)
442
443 DWORD cbBytesWritten;
444 memset(&pData->overlappedSend, 0, sizeof(pData->overlappedSend));
445 pData->overlappedSend.hEvent = pData->hEventSend;
446
447 if (!WriteFile(pData->hDeviceFile, &pData->aSendQueue[pData->iSendQueueTail], cbProcessed, &cbBytesWritten, &pData->overlappedSend))
448 {
449 DWORD dwRet = GetLastError();
450 if (dwRet == ERROR_IO_PENDING)
451 {
452 /*
453 * write blocked, wait ...
454 */
455 dwRet = WaitForMultipleObjects(2, haWait, FALSE, INFINITE);
456 if (dwRet != WAIT_OBJECT_0)
457 break;
458 }
459 else
460 rc = RTErrConvertFromWin32(dwRet);
461 }
462
463#endif
464
465 if (VBOX_SUCCESS(rc))
466 {
467 Assert(cbProcessed);
468 pData->iSendQueueTail++;
469 pData->iSendQueueTail &= CHAR_MAX_SEND_QUEUE_MASK;
470 }
471 else if (VBOX_FAILURE(rc))
472 {
473 LogRel(("HostSerial#%d: Serial Write failed with %Vrc; terminating send thread\n", pDrvIns->iInstance, rc));
474 return VINF_SUCCESS;
475 }
476 }
477 }
478
479 return VINF_SUCCESS;
480}
481
482/**
483 * Unblock the send thread so it can respond to a state change.
484 *
485 * @returns a VBox status code.
486 * @param pDrvIns The driver instance.
487 * @param pThread The send thread.
488 */
489static DECLCALLBACK(int) drvHostSerialWakeupSendThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
490{
491 PDRVHOSTSERIAL pData = PDMINS2DATA(pDrvIns, PDRVHOSTSERIAL);
492 int rc;
493
494 rc = RTSemEventSignal(pData->SendSem);
495 if (RT_FAILURE(rc))
496 return rc;
497
498#ifdef RT_OS_WINDOWS
499 if (!SetEvent(pData->hHaltEventSem))
500 return RTErrConvertFromWin32(GetLastError());
501#endif
502
503 return VINF_SUCCESS;
504}
505
506/* -=-=-=-=- receive thread -=-=-=-=- */
507
508/**
509 * Receive thread loop.
510 *
511 * This thread pushes data from the host serial device up the driver
512 * chain toward the serial device.
513 *
514 * @returns VINF_SUCCESS.
515 * @param ThreadSelf Thread handle to this thread.
516 * @param pvUser User argument.
517 */
518static DECLCALLBACK(int) drvHostSerialRecvThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
519{
520 PDRVHOSTSERIAL pData = PDMINS2DATA(pDrvIns, PDRVHOSTSERIAL);
521 uint8_t abBuffer[256];
522 uint8_t *pbBuffer = NULL;
523 size_t cbRemaining = 0; /* start by reading host data */
524 int rc = VINF_SUCCESS;
525
526 if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
527 return VINF_SUCCESS;
528
529#ifdef RT_OS_WINDOWS
530 HANDLE haWait[2];
531 haWait[0] = pData->hEventRecv;
532 haWait[1] = pData->hHaltEventSem;
533#endif
534
535 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
536 {
537 if (!cbRemaining)
538 {
539 /* Get a block of data from the host serial device. */
540
541#if defined(RT_OS_LINUX)
542
543 size_t cbRead;
544 struct pollfd aFDs[2];
545 aFDs[0].fd = pData->DeviceFile;
546 aFDs[0].events = POLLIN;
547 aFDs[0].revents = 0;
548 aFDs[1].fd = pData->WakeupPipeR;
549 aFDs[1].events = POLLIN | POLLERR | POLLHUP;
550 aFDs[1].revents = 0;
551 rc = poll(aFDs, ELEMENTS(aFDs), -1);
552 if (rc < 0)
553 {
554 /* poll failed for whatever reason */
555 break;
556 }
557 /* this might have changed in the meantime */
558 if (pThread->enmState != PDMTHREADSTATE_RUNNING)
559 break;
560 if (rc > 0 && aFDs[1].revents)
561 {
562 if (aFDs[1].revents & (POLLHUP | POLLERR | POLLNVAL))
563 break;
564 /* notification to terminate -- drain the pipe */
565 char ch;
566 size_t cbRead;
567 RTFileRead(pData->WakeupPipeR, &ch, 1, &cbRead);
568 continue;
569 }
570 rc = RTFileRead(pData->DeviceFile, abBuffer, sizeof(abBuffer), &cbRead);
571 if (VBOX_FAILURE(rc))
572 {
573 LogRel(("HostSerial#%d: Read failed with %Vrc, terminating the worker thread.\n", pDrvIns->iInstance, rc));
574 break;
575 }
576 cbRemaining = cbRead;
577
578#elif defined(RT_OS_WINDOWS)
579
580 DWORD dwEventMask = 0;
581 DWORD dwNumberOfBytesTransferred;
582
583 memset(&pData->overlappedRecv, 0, sizeof(pData->overlappedRecv));
584 pData->overlappedRecv.hEvent = pData->hEventRecv;
585
586 if (!WaitCommEvent(pData->hDeviceFile, &dwEventMask, &pData->overlappedRecv))
587 {
588 DWORD dwRet = GetLastError();
589 if (dwRet == ERROR_IO_PENDING)
590 {
591 dwRet = WaitForMultipleObjects(2, haWait, FALSE, INFINITE);
592 if (dwRet != WAIT_OBJECT_0)
593 {
594 /* notification to terminate */
595 break;
596 }
597 }
598 else
599 {
600 LogRel(("HostSerial#%d: Wait failed with error %Vrc; terminating the worker thread.\n", pDrvIns->iInstance, RTErrConvertFromWin32(dwRet)));
601 break;
602 }
603 }
604 /* this might have changed in the meantime */
605 if (pThread->enmState != PDMTHREADSTATE_RUNNING)
606 break;
607 if (!ReadFile(pData->hDeviceFile, abBuffer, sizeof(abBuffer), &dwNumberOfBytesTransferred, &pData->overlappedRecv))
608 {
609 LogRel(("HostSerial#%d: Read failed with error %Vrc; terminating the worker thread.\n", pDrvIns->iInstance, RTErrConvertFromWin32(GetLastError())));
610 break;
611 }
612 cbRemaining = dwNumberOfBytesTransferred;
613
614#endif
615
616 Log(("Read %d bytes.\n", cbRemaining));
617 pbBuffer = abBuffer;
618 }
619 else
620 {
621 /* Send data to the guest. */
622 size_t cbProcessed = cbRemaining;
623 rc = pData->pDrvCharPort->pfnNotifyRead(pData->pDrvCharPort, pbBuffer, &cbProcessed);
624 if (VBOX_SUCCESS(rc))
625 {
626 Assert(cbProcessed); Assert(cbProcessed <= cbRemaining);
627 pbBuffer += cbProcessed;
628 cbRemaining -= cbProcessed;
629 STAM_COUNTER_ADD(&pData->StatBytesRead, cbProcessed);
630 }
631 else if (rc == VERR_TIMEOUT)
632 {
633 /* Normal case, just means that the guest didn't accept a new
634 * character before the timeout elapsed. Just retry. */
635 rc = VINF_SUCCESS;
636 }
637 else
638 {
639 LogRel(("HostSerial#%d: NotifyRead failed with %Vrc, terminating the worker thread.\n", pDrvIns->iInstance, rc));
640 break;
641 }
642 }
643 }
644
645 return VINF_SUCCESS;
646}
647
648/**
649 * Unblock the send thread so it can respond to a state change.
650 *
651 * @returns a VBox status code.
652 * @param pDrvIns The driver instance.
653 * @param pThread The send thread.
654 */
655static DECLCALLBACK(int) drvHostSerialWakeupRecvThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
656{
657 PDRVHOSTSERIAL pData = PDMINS2DATA(pDrvIns, PDRVHOSTSERIAL);
658#ifdef RT_OS_LINUX
659 return RTFileWrite(pData->WakeupPipeW, "", 1, NULL);
660#elif defined(RT_OS_WINDOWS)
661 if (!SetEvent(pData->hHaltEventSem))
662 return RTErrConvertFromWin32(GetLastError());
663 return VINF_SUCCESS;
664#else
665# error adapt me!
666#endif
667}
668
669/* -=-=-=-=- Monitor thread -=-=-=-=- */
670
671/**
672 * Monitor thread loop.
673 *
674 * This thread monitors the status lines and notifies the device
675 * if they change.
676 *
677 * @returns VINF_SUCCESS.
678 * @param ThreadSelf Thread handle to this thread.
679 * @param pvUser User argument.
680 */
681static DECLCALLBACK(int) drvHostSerialMonitorThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
682{
683 PDRVHOSTSERIAL pData = PDMINS2DATA(pDrvIns, PDRVHOSTSERIAL);
684 int rc = VINF_SUCCESS;
685
686#if defined (RT_OS_LINUX)
687 unsigned uStatusLinesToCheck = 0;
688
689 uStatusLinesToCheck = TIOCM_CAR | TIOCM_RNG | TIOCM_LE | TIOCM_CTS;
690#endif
691
692 while (pThread->enmState == PDMTHREADSTATE_RUNNING)
693 {
694 PDMICHARSTATUSLINES newStatusLine = 0;
695
696#if defined(RT_OS_LINUX)
697 unsigned int statusLines;
698
699 /*
700 * Wait for status line change.
701 */
702 rc = ioctl(pData->DeviceFile, TIOCMIWAIT, &uStatusLinesToCheck);
703 if (pThread->enmState != PDMTHREADSTATE_RUNNING)
704 break;
705
706 ioctl(pData->DeviceFile, TIOCMGET, &statusLines);
707
708 if (statusLines & TIOCM_CAR)
709 newStatusLine |= PDM_ICHAR_STATUS_LINES_DCD;
710 if (statusLines & TIOCM_RNG)
711 newStatusLine |= PDM_ICHAR_STATUS_LINES_RI;
712 if (statusLines & TIOCM_LE)
713 newStatusLine |= PDM_ICHAR_STATUS_LINES_DSR;
714 if (statusLines & TIOCM_CTS)
715 newStatusLine |= PDM_ICHAR_STATUS_LINES_CTS;
716 rc = pData->pDrvCharPort->pfnNotifyStatusLinesChanged(pData->pDrvCharPort, newStatusLine);
717#endif
718 }
719
720 return VINF_SUCCESS;
721}
722
723/**
724 * Unblock the monitor thread so it can respond to a state change.
725 *
726 * @returns a VBox status code.
727 * @param pDrvIns The driver instance.
728 * @param pThread The send thread.
729 */
730static DECLCALLBACK(int) drvHostSerialWakeupMonitorThread(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
731{
732 PDRVHOSTSERIAL pData = PDMINS2DATA(pDrvIns, PDRVHOSTSERIAL);
733 int rc = VINF_SUCCESS;
734#if defined(RT_OS_LINUX)
735 /*
736 * Linux is a bit difficult as the thread is sleeping in an ioctl call.
737 * So there is no way to have a wakeup pipe.
738 * Thatswhy we set the serial device into loopback mode and change one of the
739 * modem control bits.
740 * This should make the ioctl call return.
741 */
742 rc = ioctl(pData->DeviceFile, TIOCMBIS, TIOCM_LOOP);
743 if (rc < 0)
744 AssertMsgFailed(("%s: Setting device into loopback mode failed. Cannot wake up the thread!!\n", __FUNCTION__));
745
746 rc = ioctl(pData->DeviceFile, TIOCMBIS, TIOCM_RTS);
747 if (rc < 0)
748 AssertMsgFailed(("%s: Setting bit failed. Cannot wake up thread!!\n", __FUNCTION__));
749
750 /*
751 * Set serial device into normal state.
752 */
753 rc = ioctl(pData->DeviceFile, TIOCMBIC, TIOCM_LOOP);
754 if (rc < 0)
755 AssertMsgFailed(("%s: Setting device into normal mode failed. Device is not in a working state!!\n", __FUNCTION__));
756
757#elif defined(RT_OS_WINDOWS)
758 /** @todo */
759#else
760# error adapt me!
761#endif
762
763 return rc;
764}
765
766/**
767 * Set the modem lines.
768 *
769 * @returns VBox status code
770 * @param pInterface Pointer to the interface structure.
771 * @param RequestToSend Set to 1 if this control line should be made active.
772 * @param DataTerminalReady Set to 1 if this control line should be made active.
773 */
774static DECLCALLBACK(int) drvHostSerialSetModemLines(PPDMICHAR pInterface, unsigned RequestToSend, unsigned DataTerminalReady)
775{
776#ifdef RT_OS_LINUX
777 PDRVHOSTSERIAL pData = PDMICHAR_2_DRVHOSTSERIAL(pInterface);
778 int modemState = 0;
779
780 if (RequestToSend)
781 {
782 modemState |= TIOCM_RTS;
783 }
784
785 if (DataTerminalReady)
786 {
787 modemState |= TIOCM_DTR;
788 }
789
790 ioctl(pData->DeviceFile, TIOCMBIS, &modemState);
791#endif
792
793 return VINF_SUCCESS;
794}
795
796/* -=-=-=-=- driver interface -=-=-=-=- */
797
798/**
799 * Construct a char driver instance.
800 *
801 * @returns VBox status.
802 * @param pDrvIns The driver instance data.
803 * If the registration structure is needed,
804 * pDrvIns->pDrvReg points to it.
805 * @param pCfgHandle Configuration node handle for the driver. Use this to
806 * obtain the configuration of the driver instance. It's
807 * also found in pDrvIns->pCfgHandle as it's expected to
808 * be used frequently in this function.
809 */
810static DECLCALLBACK(int) drvHostSerialConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfgHandle)
811{
812 PDRVHOSTSERIAL pData = PDMINS2DATA(pDrvIns, PDRVHOSTSERIAL);
813 LogFlow(("%s: iInstance=%d\n", __FUNCTION__, pDrvIns->iInstance));
814
815 /*
816 * Init basic data members and interfaces.
817 */
818#ifdef RT_OS_LINUX
819 pData->DeviceFile = NIL_RTFILE;
820 pData->WakeupPipeR = NIL_RTFILE;
821 pData->WakeupPipeW = NIL_RTFILE;
822#endif
823 /* IBase. */
824 pDrvIns->IBase.pfnQueryInterface = drvHostSerialQueryInterface;
825 /* IChar. */
826 pData->IChar.pfnWrite = drvHostSerialWrite;
827 pData->IChar.pfnSetParameters = drvHostSerialSetParameters;
828 pData->IChar.pfnSetModemLines = drvHostSerialSetModemLines;
829
830 /*
831 * Query configuration.
832 */
833 /* Device */
834 int rc = CFGMR3QueryStringAlloc(pCfgHandle, "DevicePath", &pData->pszDevicePath);
835 if (VBOX_FAILURE(rc))
836 {
837 AssertMsgFailed(("Configuration error: query for \"DevicePath\" string returned %Vra.\n", rc));
838 return rc;
839 }
840
841 /*
842 * Open the device
843 */
844#ifdef RT_OS_WINDOWS
845
846 pData->hHaltEventSem = CreateEvent(NULL, FALSE, FALSE, NULL);
847 AssertReturn(pData->hHaltEventSem != NULL, VERR_NO_MEMORY);
848
849 pData->hEventRecv = CreateEvent(NULL, FALSE, FALSE, NULL);
850 AssertReturn(pData->hEventRecv != NULL, VERR_NO_MEMORY);
851
852 pData->hEventSend = CreateEvent(NULL, FALSE, FALSE, NULL);
853 AssertReturn(pData->hEventSend != NULL, VERR_NO_MEMORY);
854
855 HANDLE hFile = CreateFile(pData->pszDevicePath,
856 GENERIC_READ | GENERIC_WRITE,
857 0, // must be opened with exclusive access
858 NULL, // no SECURITY_ATTRIBUTES structure
859 OPEN_EXISTING, // must use OPEN_EXISTING
860 FILE_FLAG_OVERLAPPED, // overlapped I/O
861 NULL); // no template file
862 if (hFile == INVALID_HANDLE_VALUE)
863 rc = RTErrConvertFromWin32(GetLastError());
864 else
865 {
866 pData->hDeviceFile = hFile;
867 /* for overlapped read */
868 if (!SetCommMask(hFile, EV_RXCHAR))
869 {
870 LogRel(("HostSerial#%d: SetCommMask failed with error %d.\n", pDrvIns->iInstance, GetLastError()));
871 return VERR_FILE_IO_ERROR;
872 }
873 rc = VINF_SUCCESS;
874 }
875
876#else
877
878 rc = RTFileOpen(&pData->DeviceFile, pData->pszDevicePath, RTFILE_O_OPEN | RTFILE_O_READWRITE);
879
880#endif
881
882 if (VBOX_FAILURE(rc))
883 {
884 AssertMsgFailed(("Could not open host device %s, rc=%Vrc\n", pData->pszDevicePath, rc));
885 switch (rc)
886 {
887 case VERR_ACCESS_DENIED:
888 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
889#ifdef RT_OS_LINUX
890 N_("Cannot open host device '%s' for read/write access. Check the permissions "
891 "of that device ('/bin/ls -l %s'): Most probably you need to be member "
892 "of the device group. Make sure that you logout/login after changing "
893 "the group settings of the current user"),
894#else
895 N_("Cannot open host device '%s' for read/write access. Check the permissions "
896 "of that device"),
897#endif
898 pData->pszDevicePath, pData->pszDevicePath);
899 default:
900 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS,
901 N_("Failed to open host device '%s'"),
902 pData->pszDevicePath);
903 }
904 }
905
906 /* Set to non blocking I/O */
907#ifdef RT_OS_LINUX
908
909 fcntl(pData->DeviceFile, F_SETFL, O_NONBLOCK);
910 int aFDs[2];
911 if (pipe(aFDs) != 0)
912 {
913 int rc = RTErrConvertFromErrno(errno);
914 AssertRC(rc);
915 return rc;
916 }
917 pData->WakeupPipeR = aFDs[0];
918 pData->WakeupPipeW = aFDs[1];
919
920#elif defined(RT_OS_WINDOWS)
921
922 /* Set the COMMTIMEOUTS to get non blocking I/O */
923 COMMTIMEOUTS comTimeout;
924
925 comTimeout.ReadIntervalTimeout = MAXDWORD;
926 comTimeout.ReadTotalTimeoutMultiplier = 0;
927 comTimeout.ReadTotalTimeoutConstant = 0;
928 comTimeout.WriteTotalTimeoutMultiplier = 0;
929 comTimeout.WriteTotalTimeoutConstant = 0;
930
931 SetCommTimeouts(pData->hDeviceFile, &comTimeout);
932
933#endif
934
935 /*
936 * Get the ICharPort interface of the above driver/device.
937 */
938 pData->pDrvCharPort = (PPDMICHARPORT)pDrvIns->pUpBase->pfnQueryInterface(pDrvIns->pUpBase, PDMINTERFACE_CHAR_PORT);
939 if (!pData->pDrvCharPort)
940 return PDMDrvHlpVMSetError(pDrvIns, VERR_PDM_MISSING_INTERFACE_ABOVE, RT_SRC_POS, N_("HostSerial#%d has no char port interface above"), pDrvIns->iInstance);
941
942 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pData->pRecvThread, pData, drvHostSerialRecvThread, drvHostSerialWakeupRecvThread, 0, RTTHREADTYPE_IO, "Serial Receive");
943 if (VBOX_FAILURE(rc))
944 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("HostSerial#%d cannot create receive thread"), pDrvIns->iInstance);
945
946 rc = RTSemEventCreate(&pData->SendSem);
947 AssertRC(rc);
948
949 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pData->pSendThread, pData, drvHostSerialSendThread, drvHostSerialWakeupSendThread, 0, RTTHREADTYPE_IO, "Serial Send");
950 if (VBOX_FAILURE(rc))
951 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("HostSerial#%d cannot create send thread"), pDrvIns->iInstance);
952
953#if defined(RT_OS_LINUX)
954 rc = PDMDrvHlpPDMThreadCreate(pDrvIns, &pData->pMonitorThread, pData, drvHostSerialMonitorThread, drvHostSerialWakeupMonitorThread, 0, RTTHREADTYPE_IO, "Serial Monitor");
955 if (VBOX_FAILURE(rc))
956 return PDMDrvHlpVMSetError(pDrvIns, rc, RT_SRC_POS, N_("HostSerial#%d cannot create monitor thread"), pDrvIns->iInstance);
957#endif
958
959 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatBytesWritten, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES, "Nr of bytes written", "/Devices/HostSerial%d/Written", pDrvIns->iInstance);
960 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatBytesRead, STAMTYPE_COUNTER, STAMVISIBILITY_USED, STAMUNIT_BYTES, "Nr of bytes read", "/Devices/HostSerial%d/Read", pDrvIns->iInstance);
961
962 return VINF_SUCCESS;
963}
964
965
966/**
967 * Destruct a char driver instance.
968 *
969 * Most VM resources are freed by the VM. This callback is provided so that
970 * any non-VM resources can be freed correctly.
971 *
972 * @param pDrvIns The driver instance data.
973 */
974static DECLCALLBACK(void) drvHostSerialDestruct(PPDMDRVINS pDrvIns)
975{
976 PDRVHOSTSERIAL pData = PDMINS2DATA(pDrvIns, PDRVHOSTSERIAL);
977
978 LogFlow(("%s: iInstance=%d\n", __FUNCTION__, pDrvIns->iInstance));
979
980 /* Empty the send queue */
981 pData->iSendQueueTail = pData->iSendQueueHead = 0;
982
983 RTSemEventDestroy(pData->SendSem);
984 pData->SendSem = NIL_RTSEMEVENT;
985
986#if defined(RT_OS_LINUX)
987
988 if (pData->WakeupPipeW != NIL_RTFILE)
989 {
990 int rc = RTFileClose(pData->WakeupPipeW);
991 AssertRC(rc);
992 pData->WakeupPipeW = NIL_RTFILE;
993 }
994 if (pData->WakeupPipeR != NIL_RTFILE)
995 {
996 int rc = RTFileClose(pData->WakeupPipeR);
997 AssertRC(rc);
998 pData->WakeupPipeR = NIL_RTFILE;
999 }
1000 if (pData->DeviceFile != NIL_RTFILE)
1001 {
1002 int rc = RTFileClose(pData->DeviceFile);
1003 AssertRC(rc);
1004 pData->DeviceFile = NIL_RTFILE;
1005 }
1006
1007#elif defined(RT_OS_WINDOWS)
1008
1009 CloseHandle(pData->hEventRecv);
1010 CloseHandle(pData->hEventSend);
1011 CancelIo(pData->hDeviceFile);
1012 CloseHandle(pData->hDeviceFile);
1013
1014#endif
1015}
1016
1017/**
1018 * Char driver registration record.
1019 */
1020const PDMDRVREG g_DrvHostSerial =
1021{
1022 /* u32Version */
1023 PDM_DRVREG_VERSION,
1024 /* szDriverName */
1025 "Host Serial",
1026 /* pszDescription */
1027 "Host serial driver.",
1028 /* fFlags */
1029 PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
1030 /* fClass. */
1031 PDM_DRVREG_CLASS_CHAR,
1032 /* cMaxInstances */
1033 ~0,
1034 /* cbInstance */
1035 sizeof(DRVHOSTSERIAL),
1036 /* pfnConstruct */
1037 drvHostSerialConstruct,
1038 /* pfnDestruct */
1039 drvHostSerialDestruct,
1040 /* pfnIOCtl */
1041 NULL,
1042 /* pfnPowerOn */
1043 NULL,
1044 /* pfnReset */
1045 NULL,
1046 /* pfnSuspend */
1047 NULL,
1048 /* pfnResume */
1049 NULL,
1050 /* pfnDetach */
1051 NULL,
1052 /** pfnPowerOff */
1053 NULL
1054};
1055
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