VirtualBox

source: vbox/trunk/src/VBox/Runtime/r3/posix/serialport-posix.cpp@ 69986

Last change on this file since 69986 was 69986, checked in by vboxsync, 7 years ago

Runtime/RTSerialPort: POSIX and Windows implementation fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.1 KB
Line 
1/* $Id: serialport-posix.cpp 69986 2017-12-07 15:46:42Z vboxsync $ */
2/** @file
3 * IPRT - Serial Port API, POSIX Implementation.
4 */
5
6/*
7 * Copyright (C) 2017 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 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#include <iprt/serialport.h>
32#include "internal/iprt.h"
33
34#include <iprt/asm.h>
35#include <iprt/assert.h>
36#include <iprt/cdefs.h>
37#include <iprt/err.h>
38#include <iprt/mem.h>
39#include <iprt/string.h>
40#include <iprt/thread.h>
41#include <iprt/time.h>
42#include "internal/magics.h"
43
44#include <errno.h>
45#ifdef RT_OS_SOLARIS
46# include <sys/termios.h>
47#else
48# include <termios.h>
49#endif
50#include <sys/types.h>
51#include <fcntl.h>
52#include <string.h>
53#include <unistd.h>
54#ifdef RT_OS_DARWIN
55# include <sys/poll.h>
56#else
57# include <sys/poll.h>
58#endif
59#include <sys/ioctl.h>
60#include <pthread.h>
61
62#ifdef RT_OS_LINUX
63/*
64 * TIOCM_LOOP is not defined in the above header files for some reason but in asm/termios.h.
65 * But inclusion of this file however leads to compilation errors because of redefinition of some
66 * structs. That's why it is defined here until a better solution is found.
67 */
68# ifndef TIOCM_LOOP
69# define TIOCM_LOOP 0x8000
70# endif
71/* For linux custom baudrate code we also need serial_struct */
72# include <linux/serial.h>
73#endif /* linux */
74
75/** Define fallback if not supported. */
76#if !defined(CMSPAR)
77# define CMSPAR 0
78#endif
79
80
81/*********************************************************************************************************************************
82* Structures and Typedefs *
83*********************************************************************************************************************************/
84
85/**
86 * Internal serial port state.
87 */
88typedef struct RTSERIALPORTINTERNAL
89{
90 /** Magic value (RTSERIALPORT_MAGIC). */
91 uint32_t u32Magic;
92 /** Flags given while opening the serial port. */
93 uint32_t fOpenFlags;
94 /** The file descriptor of the serial port. */
95 int iFd;
96 /** The status line monitor thread if enabled. */
97 RTTHREAD hMonThrd;
98 /** Flag whether the monitoring thread should shutdown. */
99 volatile bool fMonThrdShutdown;
100 /** Reading end of wakeup pipe. */
101 int iFdPipeR;
102 /** Writing end of wakeup pipe. */
103 int iFdPipeW;
104 /** Event pending mask. */
105 volatile uint32_t fEvtsPending;
106 /** The current active config (we assume no one changes this behind our back). */
107 struct termios PortCfg;
108} RTSERIALPORTINTERNAL;
109/** Pointer to the internal serial port state. */
110typedef RTSERIALPORTINTERNAL *PRTSERIALPORTINTERNAL;
111
112
113/**
114 * Baud rate conversion table descriptor.
115 */
116typedef struct RTSERIALPORTBRATECONVDESC
117{
118 /** The platform independent baud rate used by the RTSerialPort* API. */
119 uint32_t uBaudRateCfg;
120 /** The speed identifier used in the termios structure. */
121 speed_t iSpeedTermios;
122} RTSERIALPORTBRATECONVDESC;
123/** Pointer to a baud rate converions table descriptor. */
124typedef RTSERIALPORTBRATECONVDESC *PRTSERIALPORTBRATECONVDESC;
125/** Pointer to a const baud rate conversion table descriptor. */
126typedef const RTSERIALPORTBRATECONVDESC *PCRTSERIALPORTBRATECONVDESC;
127
128
129/*********************************************************************************************************************************
130* Defined Constants And Macros *
131*********************************************************************************************************************************/
132
133/** The event poller was woken up due to an external interrupt. */
134#define RTSERIALPORT_WAKEUP_PIPE_REASON_INTERRUPT 0x0
135/** The event poller was woken up due to a change in the monitored status lines. */
136#define RTSERIALPORT_WAKEUP_PIPE_REASON_STS_LINE_CHANGED 0x1
137/** The monitor thread encoutnered repeating errors querying the status lines and terminated. */
138#define RTSERIALPORT_WAKEUP_PIPE_REASON_STS_LINE_MONITOR_FAILED 0x2
139
140
141/*********************************************************************************************************************************
142* Global variables *
143*********************************************************************************************************************************/
144
145/** The baud rate conversion table. */
146static const RTSERIALPORTBRATECONVDESC s_rtSerialPortBaudrateConv[] =
147{
148 { 50, B50 },
149 { 75, B75 },
150 { 110, B110 },
151 { 134, B134 },
152 { 150, B150 },
153 { 200, B200 },
154 { 300, B300 },
155 { 600, B600 },
156 { 1200, B1200 },
157 { 1800, B1800 },
158 { 2400, B2400 },
159 { 4800, B4800 },
160 { 9600, B9600 },
161 { 19200, B19200 },
162 { 38400, B38400 },
163 { 57600, B57600 },
164 { 115200, B115200 }
165};
166
167
168
169/*********************************************************************************************************************************
170* Internal Functions *
171*********************************************************************************************************************************/
172
173/**
174 * Converts the given termios speed identifier to the baud rate used in the API.
175 *
176 * @returns Baud rate or 0 if not a standard baud rate
177 */
178DECLINLINE(uint32_t) rtSerialPortGetBaudrateFromTermiosSpeed(speed_t enmSpeed)
179{
180 for (unsigned i = 0; i < RT_ELEMENTS(s_rtSerialPortBaudrateConv); i++)
181 {
182 if (s_rtSerialPortBaudrateConv[i].iSpeedTermios == enmSpeed)
183 return s_rtSerialPortBaudrateConv[i].uBaudRateCfg;
184 }
185
186 return 0;
187}
188
189
190/**
191 * Converts the given baud rate to proper termios speed identifier.
192 *
193 * @returns Speed identifier if available or B0 if no matching speed for the baud rate
194 * could be found.
195 * @param uBaudRate The baud rate to convert.
196 */
197DECLINLINE(speed_t) rtSerialPortGetTermiosSpeedFromBaudrate(uint32_t uBaudRate)
198{
199 for (unsigned i = 0; i < RT_ELEMENTS(s_rtSerialPortBaudrateConv); i++)
200 {
201 if (s_rtSerialPortBaudrateConv[i].uBaudRateCfg == uBaudRate)
202 return s_rtSerialPortBaudrateConv[i].iSpeedTermios;
203 }
204
205 return B0;
206}
207
208
209/**
210 * Tries to set the default config on the given serial port.
211 *
212 * @returns IPRT status code.
213 * @param pThis The internal serial port instance data.
214 */
215static int rtSerialPortSetDefaultCfg(PRTSERIALPORTINTERNAL pThis)
216{
217 pThis->PortCfg.c_iflag = INPCK; /* Input parity checking. */
218 cfsetispeed(&pThis->PortCfg, B9600);
219 cfsetospeed(&pThis->PortCfg, B9600);
220 pThis->PortCfg.c_cflag = CS8 | CLOCAL; /* 8 data bits, ignore modem control lines. */
221 if (pThis->fOpenFlags & RTSERIALPORT_OPEN_F_READ)
222 pThis->PortCfg.c_cflag |= CREAD; /* Enable receiver. */
223
224 /* Set to raw input mode. */
225 pThis->PortCfg.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHONL | ECHOK | ISIG | IEXTEN);
226 pThis->PortCfg.c_cc[VMIN] = 0; /* Achieve non-blocking behavior. */
227 pThis->PortCfg.c_cc[VTIME] = 0;
228
229 int rc = VINF_SUCCESS;
230 int rcPsx = tcflush(pThis->iFd, TCIOFLUSH);
231 if (!rcPsx)
232 {
233 rcPsx = tcsetattr(pThis->iFd, TCSANOW, &pThis->PortCfg);
234 if (rcPsx == -1)
235 rc = RTErrConvertFromErrno(errno);
236
237 if (RT_SUCCESS(rc))
238 {
239#ifdef RT_OS_LINUX
240 if (pThis->fOpenFlags & RTSERIALPORT_OPEN_F_ENABLE_LOOPBACK)
241 {
242 int fTiocmSet = TIOCM_LOOP;
243 rcPsx = ioctl(pThis->iFd, TIOCMBIS, &fTiocmSet);
244 if (rcPsx == -1)
245 rc = RTErrConvertFromErrno(errno);
246 }
247 else
248 {
249 /* Make sure it is clear. */
250 int fTiocmClear = TIOCM_LOOP;
251 rcPsx = ioctl(pThis->iFd, TIOCMBIC, &fTiocmClear);
252 if (rcPsx == -1)
253 rc = RTErrConvertFromErrno(errno);
254 }
255#else
256 if (pThis->fOpenFlags & RTSERIALPORT_OPEN_F_ENABLE_LOOPBACK)
257 return VERR_NOT_SUPPORTED;
258#endif
259 }
260 }
261 else
262 rc = RTErrConvertFromErrno(errno);
263
264 return rc;
265}
266
267
268/**
269 * Converts the given serial port config to the appropriate termios counterpart.
270 *
271 * @returns IPRT status code.
272 * @param pCfg Pointer to the serial port config descriptor.
273 * @param pTermios Pointer to the termios structure to fill.
274 * @param pErrInfo Additional error to be set when the conversion fails.
275 */
276static int rtSerialPortCfg2Termios(PCRTSERIALPORTCFG pCfg, struct termios *pTermios, PRTERRINFO pErrInfo)
277{
278 RT_NOREF(pErrInfo); /** @todo Make use of the error info. */
279 speed_t enmSpeed = rtSerialPortGetTermiosSpeedFromBaudrate(pCfg->uBaudRate);
280 if (enmSpeed != B0)
281 {
282 tcflag_t const fCFlagMask = (CS5 | CS6 | CS7 | CS8 | CSTOPB | PARENB | PARODD | CMSPAR);
283 tcflag_t fCFlagNew = 0;
284
285 switch (pCfg->enmDataBitCount)
286 {
287 case RTSERIALPORTDATABITS_5BITS:
288 fCFlagNew |= CS5;
289 break;
290 case RTSERIALPORTDATABITS_6BITS:
291 fCFlagNew |= CS6;
292 break;
293 case RTSERIALPORTDATABITS_7BITS:
294 fCFlagNew |= CS7;
295 break;
296 case RTSERIALPORTDATABITS_8BITS:
297 fCFlagNew |= CS8;
298 break;
299 default:
300 AssertFailed();
301 return VERR_INVALID_PARAMETER;
302 }
303
304 switch (pCfg->enmParity)
305 {
306 case RTSERIALPORTPARITY_NONE:
307 break;
308 case RTSERIALPORTPARITY_EVEN:
309 fCFlagNew |= PARENB;
310 break;
311 case RTSERIALPORTPARITY_ODD:
312 fCFlagNew |= PARENB | PARODD;
313 break;
314#if CMSPAR != 0
315 case RTSERIALPORTPARITY_MARK:
316 fCFlagNew |= PARENB | CMSPAR | PARODD;
317 break;
318 case RTSERIALPORTPARITY_SPACE:
319 fCFlagNew |= PARENB | CMSPAR;
320 break;
321#else
322 case RTSERIALPORTPARITY_MARK:
323 case RTSERIALPORTPARITY_SPACE:
324 return VERR_NOT_SUPPORTED;
325#endif
326 default:
327 AssertFailed();
328 return VERR_INVALID_PARAMETER;
329 }
330
331 switch (pCfg->enmStopBitCount)
332 {
333 case RTSERIALPORTSTOPBITS_ONE:
334 break;
335 case RTSERIALPORTSTOPBITS_ONEPOINTFIVE:
336 if (pCfg->enmDataBitCount == RTSERIALPORTDATABITS_5BITS)
337 fCFlagNew |= CSTOPB;
338 else
339 return VERR_NOT_SUPPORTED;
340 break;
341 case RTSERIALPORTSTOPBITS_TWO:
342 if (pCfg->enmDataBitCount != RTSERIALPORTDATABITS_5BITS)
343 fCFlagNew |= CSTOPB;
344 else
345 return VERR_NOT_SUPPORTED;
346 break;
347 default:
348 AssertFailed();
349 return VERR_INVALID_PARAMETER;
350 }
351
352 /* Assign new flags. */
353 pTermios->c_cflag = (pTermios->c_cflag & ~fCFlagMask) | fCFlagNew;
354 }
355 else
356 return VERR_SERIALPORT_INVALID_BAUDRATE;
357
358#ifdef RT_OS_LINUX
359 /** @todo Handle custom baudrates supported by Linux. */
360#endif
361
362 return VINF_SUCCESS;
363}
364
365
366/**
367 * Converts the given termios structure to an appropriate serial port config.
368 *
369 * @returns IPRT status code.
370 * @param pTermios The termios structure to convert.
371 * @param pCfg The serial port config to fill in.
372 */
373static int rtSerialPortTermios2Cfg(struct termios *pTermios, PRTSERIALPORTCFG pCfg)
374{
375 int rc = VINF_SUCCESS;
376 bool f5DataBits = false;
377 speed_t enmSpeedIn = cfgetispeed(pTermios);
378 Assert(enmSpeedIn == cfgetospeed(pTermios)); /* Should always be the same. */
379
380 pCfg->uBaudRate = rtSerialPortGetBaudrateFromTermiosSpeed(enmSpeedIn);
381 if (!pCfg->uBaudRate)
382 rc = VERR_SERIALPORT_INVALID_BAUDRATE;
383
384 switch (pTermios->c_cflag & CSIZE)
385 {
386 case CS5:
387 pCfg->enmDataBitCount = RTSERIALPORTDATABITS_5BITS;
388 f5DataBits = true;
389 break;
390 case CS6:
391 pCfg->enmDataBitCount = RTSERIALPORTDATABITS_6BITS;
392 break;
393 case CS7:
394 pCfg->enmDataBitCount = RTSERIALPORTDATABITS_7BITS;
395 break;
396 case CS8:
397 pCfg->enmDataBitCount = RTSERIALPORTDATABITS_8BITS;
398 break;
399 default:
400 AssertFailed(); /* Should not happen. */
401 pCfg->enmDataBitCount = RTSERIALPORTDATABITS_INVALID;
402 rc = RT_FAILURE(rc) ? rc : VERR_INVALID_PARAMETER;
403 }
404
405 /* Convert parity. */
406 if (pTermios->c_cflag & PARENB)
407 {
408 /*
409 * CMSPAR is not supported on all systems, especially OS X. As configuring
410 * mark/space parity there is not supported and we start from a known config
411 * when opening the serial port it is not required to check for this here.
412 */
413#if CMSPAR == 0
414 bool fCmsParSet = RT_BOOL(pTermios->c_cflag & CMSPAR);
415#else
416 bool fCmsParSet = false;
417#endif
418 if (pTermios->c_cflag & PARODD)
419 pCfg->enmParity = fCmsParSet ? RTSERIALPORTPARITY_MARK : RTSERIALPORTPARITY_ODD;
420 else
421 pCfg->enmParity = fCmsParSet ? RTSERIALPORTPARITY_SPACE: RTSERIALPORTPARITY_EVEN;
422 }
423 else
424 pCfg->enmParity = RTSERIALPORTPARITY_NONE;
425
426 /*
427 * 1.5 stop bits are used with a data count of 5 bits when a UART derived from the 8250
428 * is used.
429 */
430 if (pTermios->c_cflag & CSTOPB)
431 pCfg->enmStopBitCount = f5DataBits ? RTSERIALPORTSTOPBITS_ONEPOINTFIVE : RTSERIALPORTSTOPBITS_TWO;
432 else
433 pCfg->enmStopBitCount = RTSERIALPORTSTOPBITS_ONE;
434
435 return rc;
436}
437
438
439/**
440 * Wakes up any thread polling for a serial port event with the given reason.
441 *
442 * @returns IPRT status code.
443 * @param pThis The internal serial port instance data.
444 * @param bWakeupReason The wakeup reason to pass to the event poller.
445 */
446DECLINLINE(int) rtSerialPortWakeupEvtPoller(PRTSERIALPORTINTERNAL pThis, uint8_t bWakeupReason)
447{
448 int rcPsx = write(pThis->iFdPipeW, &bWakeupReason, 1);
449 if (rcPsx != 1)
450 return RTErrConvertFromErrno(errno);
451
452 return VINF_SUCCESS;
453}
454
455
456/**
457 * The status line monitor thread worker.
458 *
459 * @returns IPRT status code.
460 * @param ThreadSelf Thread handle to this thread.
461 * @param pvUser User argument.
462 */
463static DECLCALLBACK(int) rtSerialPortStsLineMonitorThrd(RTTHREAD hThreadSelf, void *pvUser)
464{
465 RT_NOREF(hThreadSelf);
466 PRTSERIALPORTINTERNAL pThis = (PRTSERIALPORTINTERNAL)pvUser;
467 unsigned long const fStsLinesChk = TIOCM_CAR | TIOCM_RNG | TIOCM_DSR | TIOCM_CTS;
468 int rc = VINF_SUCCESS;
469 uint32_t fStsLinesOld = 0;
470 uint32_t cStsLineGetErrors = 0;
471#ifdef RT_OS_LINUX
472 bool fPoll = false;
473#endif
474
475 RTThreadUserSignal(hThreadSelf);
476
477 int rcPsx = ioctl(pThis->iFd, TIOCMGET, &fStsLinesOld);
478 if (rcPsx == -1)
479 {
480 ASMAtomicXchgBool(&pThis->fMonThrdShutdown, true);
481 return RTErrConvertFromErrno(errno);
482 }
483
484 while ( !pThis->fMonThrdShutdown
485 && RT_SUCCESS(rc))
486 {
487# ifdef RT_OS_LINUX
488 /*
489 * Wait for status line change.
490 *
491 * XXX In Linux, if a thread calls tcsetattr while the monitor thread is
492 * waiting in ioctl for a modem status change then 8250.c wrongly disables
493 * modem irqs and so the monitor thread never gets released. The workaround
494 * is to send a signal after each tcsetattr.
495 *
496 * TIOCMIWAIT doesn't work for the DSR line with TIOCM_DSR set
497 * (see http://lxr.linux.no/#linux+v4.7/drivers/usb/class/cdc-acm.c#L949)
498 * However as it is possible to query the line state we will not just clear
499 * the TIOCM_DSR bit from the lines to check but resort to the polling
500 * approach just like on other hosts.
501 */
502 if (!fPoll)
503 {
504 rcPsx = ioctl(pThis->iFd, TIOCMIWAIT, fStsLinesChk);
505 if (!rcPsx)
506 {
507 rc = rtSerialPortWakeupEvtPoller(pThis, RTSERIALPORT_WAKEUP_PIPE_REASON_STS_LINE_CHANGED);
508 if (RT_FAILURE(rc))
509 break;
510 }
511 else if (rcPsx == -1 && errno != EINTR)
512 fPoll = true;
513 }
514 else
515#endif
516 {
517 uint32_t fStsLines = 0;
518 rcPsx = ioctl(pThis->iFd, TIOCMGET, &fStsLines);
519 if (!rcPsx)
520 {
521 cStsLineGetErrors = 0; /* Reset the error counter once we had one successful query. */
522
523 if (((fStsLines ^ fStsLinesOld) & fStsLinesChk))
524 {
525 rc = rtSerialPortWakeupEvtPoller(pThis, RTSERIALPORT_WAKEUP_PIPE_REASON_STS_LINE_CHANGED);
526 if (RT_FAILURE(rc))
527 break;
528
529 fStsLinesOld = fStsLines;
530 }
531 else /* No change, sleep for a bit. */
532 RTThreadSleep(100 /*ms*/);
533 }
534 else if (rcPsx == -1 && errno != EINTR)
535 {
536 /*
537 * If querying the status line fails too often we have to shut down the
538 * thread and notify the user of the serial port.
539 */
540 if (cStsLineGetErrors++ >= 10)
541 {
542 rc = RTErrConvertFromErrno(errno);
543 rtSerialPortWakeupEvtPoller(pThis, RTSERIALPORT_WAKEUP_PIPE_REASON_STS_LINE_MONITOR_FAILED);
544 break;
545 }
546
547 RTThreadSleep(100 /*ms*/);
548 }
549 }
550 }
551
552 ASMAtomicXchgBool(&pThis->fMonThrdShutdown, true);
553 return rc;
554}
555
556
557/**
558 * Creates the status line monitoring thread.
559 *
560 * @returns IPRT status code.
561 * @param pThis The internal serial port instance data.
562 */
563static int rtSerialPortMonitorThreadCreate(PRTSERIALPORTINTERNAL pThis)
564{
565 int rc = VINF_SUCCESS;
566
567 /*
568 * Check whether querying the status lines is supported at all, pseudo terminals
569 * don't support it so an error returned in that case.
570 */
571 uint32_t fStsLines = 0;
572 int rcPsx = ioctl(pThis->iFd, TIOCMGET, &fStsLines);
573 if (!rcPsx)
574 {
575 pThis->fMonThrdShutdown = false;
576 rc = RTThreadCreate(&pThis->hMonThrd, rtSerialPortStsLineMonitorThrd, pThis, 0 /*cbStack*/,
577 RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE, "IPRT-SerPortMon");
578 if (RT_SUCCESS(rc))
579 {
580 /* Wait for the thread to start up. */
581 rc = RTThreadUserWait(pThis->hMonThrd, 20*RT_MS_1SEC);
582 if ( rc == VERR_TIMEOUT
583 || pThis->fMonThrdShutdown)
584 {
585 /* Startup failed, try to reap the thread. */
586 int rcThrd;
587 rc = RTThreadWait(pThis->hMonThrd, 20*RT_MS_1SEC, &rcThrd);
588 if (RT_SUCCESS(rc))
589 rc = rcThrd;
590 else
591 rc = VERR_INTERNAL_ERROR;
592 /* The thread is lost otherwise. */
593 }
594 }
595 }
596 else if (errno == ENOTTY)
597 rc = VERR_NOT_SUPPORTED;
598 else
599 rc = RTErrConvertFromErrno(errno);
600
601 return rc;
602}
603
604
605/**
606 * Shuts down the status line monitor thread.
607 *
608 * @returns nothing.
609 * @param pThis The internal serial port instance data.
610 */
611static void rtSerialPortMonitorThreadShutdown(PRTSERIALPORTINTERNAL pThis)
612{
613 bool fShutDown = ASMAtomicXchgBool(&pThis->fMonThrdShutdown, true);
614 if (!fShutDown)
615 {
616 int rc = RTThreadPoke(pThis->hMonThrd);
617 AssertRC(rc);
618 }
619
620 int rcThrd = VINF_SUCCESS;
621 int rc = RTThreadWait(pThis->hMonThrd, 20*RT_MS_1SEC, &rcThrd);
622 AssertRC(rc);
623 AssertRC(rcThrd);
624}
625
626
627RTDECL(int) RTSerialPortOpen(PRTSERIALPORT phSerialPort, const char *pszPortAddress, uint32_t fFlags)
628{
629 AssertPtrReturn(phSerialPort, VERR_INVALID_POINTER);
630 AssertReturn(VALID_PTR(pszPortAddress) && *pszPortAddress != '\0', VERR_INVALID_PARAMETER);
631 AssertReturn(!(fFlags & ~RTSERIALPORT_OPEN_F_VALID_MASK), VERR_INVALID_PARAMETER);
632 AssertReturn((fFlags & RTSERIALPORT_OPEN_F_READ) || (fFlags & RTSERIALPORT_OPEN_F_WRITE),
633 VERR_INVALID_PARAMETER);
634
635 int rc = VINF_SUCCESS;
636 PRTSERIALPORTINTERNAL pThis = (PRTSERIALPORTINTERNAL)RTMemAllocZ(sizeof(*pThis));
637 if (pThis)
638 {
639 int fPsxFlags = O_NOCTTY;
640
641 if ((fFlags & RTSERIALPORT_OPEN_F_READ) && !(fFlags & RTSERIALPORT_OPEN_F_WRITE))
642 fPsxFlags |= O_RDONLY;
643 else if (!(fFlags & RTSERIALPORT_OPEN_F_READ) && (fFlags & RTSERIALPORT_OPEN_F_WRITE))
644 fPsxFlags |= O_WRONLY;
645 else
646 fPsxFlags |= O_RDWR;
647
648 pThis->u32Magic = RTSERIALPORT_MAGIC;
649 pThis->fOpenFlags = fFlags;
650 pThis->fEvtsPending = 0;
651 pThis->iFd = open(pszPortAddress, fPsxFlags);
652 if (pThis->iFd != -1)
653 {
654 /* Create wakeup pipe for the event API. */
655 int aPipeFds[2];
656 int rcPsx = pipe(&aPipeFds[0]);
657 if (!rcPsx)
658 {
659 /* Make the pipes close on exec. */
660 pThis->iFdPipeR = aPipeFds[0];
661 pThis->iFdPipeW = aPipeFds[1];
662
663 if (fcntl(pThis->iFdPipeR, F_SETFD, FD_CLOEXEC))
664 rc = RTErrConvertFromErrno(errno);
665
666 if ( RT_SUCCESS(rc)
667 && fcntl(pThis->iFdPipeW, F_SETFD, FD_CLOEXEC))
668 rc = RTErrConvertFromErrno(errno);
669
670 if (RT_SUCCESS(rc))
671 {
672 rc = rtSerialPortSetDefaultCfg(pThis);
673 if ( RT_SUCCESS(rc)
674 && (fFlags & RTSERIALPORT_OPEN_F_SUPPORT_STATUS_LINE_MONITORING))
675 rc = rtSerialPortMonitorThreadCreate(pThis);
676
677 if (RT_SUCCESS(rc))
678 {
679 *phSerialPort = pThis;
680 return VINF_SUCCESS;
681 }
682 }
683
684 close(pThis->iFdPipeR);
685 close(pThis->iFdPipeW);
686 }
687 else
688 rc = RTErrConvertFromErrno(errno);
689
690 close(pThis->iFd);
691 }
692 else
693 rc = RTErrConvertFromErrno(errno);
694
695 RTMemFree(pThis);
696 }
697 else
698 rc = VERR_NO_MEMORY;
699
700 return rc;
701}
702
703
704RTDECL(int) RTSerialPortClose(RTSERIALPORT hSerialPort)
705{
706 PRTSERIALPORTINTERNAL pThis = hSerialPort;
707 if (pThis == NIL_RTSERIALPORT)
708 return VINF_SUCCESS;
709 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
710 AssertReturn(pThis->u32Magic == RTSERIALPORT_MAGIC, VERR_INVALID_HANDLE);
711
712 /*
713 * Do the cleanup.
714 */
715 AssertReturn(ASMAtomicCmpXchgU32(&pThis->u32Magic, RTSERIALPORT_MAGIC_DEAD, RTSERIALPORT_MAGIC), VERR_INVALID_HANDLE);
716
717 if (pThis->fOpenFlags & RTSERIALPORT_OPEN_F_SUPPORT_STATUS_LINE_MONITORING)
718 rtSerialPortMonitorThreadShutdown(pThis);
719
720 close(pThis->iFd);
721 close(pThis->iFdPipeR);
722 close(pThis->iFdPipeW);
723 RTMemFree(pThis);
724 return VINF_SUCCESS;
725}
726
727
728RTDECL(RTHCINTPTR) RTSerialPortToNative(RTSERIALPORT hSerialPort)
729{
730 PRTSERIALPORTINTERNAL pThis = hSerialPort;
731 AssertPtrReturn(pThis, -1);
732 AssertReturn(pThis->u32Magic == RTSERIALPORT_MAGIC, -1);
733
734 return pThis->iFd;
735}
736
737
738RTDECL(int) RTSerialPortRead(RTSERIALPORT hSerialPort, void *pvBuf, size_t cbToRead, size_t *pcbRead)
739{
740 RT_NOREF(hSerialPort, pvBuf, cbToRead, pcbRead);
741 return VERR_NOT_IMPLEMENTED;
742}
743
744
745RTDECL(int) RTSerialPortReadNB(RTSERIALPORT hSerialPort, void *pvBuf, size_t cbToRead, size_t *pcbRead)
746{
747 PRTSERIALPORTINTERNAL pThis = hSerialPort;
748 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
749 AssertReturn(pThis->u32Magic == RTSERIALPORT_MAGIC, VERR_INVALID_HANDLE);
750 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
751 AssertReturn(cbToRead > 0, VERR_INVALID_PARAMETER);
752 AssertPtrReturn(pcbRead, VERR_INVALID_POINTER);
753
754 *pcbRead = 0;
755
756 int rc = VINF_SUCCESS;
757 ssize_t cbThisRead = read(pThis->iFd, pvBuf, cbToRead);
758 if (cbThisRead > 0)
759 {
760 /*
761 * The read data needs to be scanned for the BREAK condition marker encoded in the data stream,
762 * if break detection was enabled during open.
763 */
764 if (pThis->fOpenFlags & RTSERIALPORT_OPEN_F_DETECT_BREAK_CONDITION)
765 { /** @todo */ }
766
767 *pcbRead = cbThisRead;
768 }
769 else if (cbThisRead == 0 || errno == EAGAIN || errno == EWOULDBLOCK)
770 rc = VINF_TRY_AGAIN;
771 else
772 rc = RTErrConvertFromErrno(errno);
773
774 return rc;
775}
776
777
778RTDECL(int) RTSerialPortWrite(RTSERIALPORT hSerialPort, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
779{
780 RT_NOREF(hSerialPort, pvBuf, cbToWrite, pcbWritten);
781 return VERR_NOT_IMPLEMENTED;
782}
783
784
785RTDECL(int) RTSerialPortWriteNB(RTSERIALPORT hSerialPort, const void *pvBuf, size_t cbToWrite, size_t *pcbWritten)
786{
787 PRTSERIALPORTINTERNAL pThis = hSerialPort;
788 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
789 AssertReturn(pThis->u32Magic == RTSERIALPORT_MAGIC, VERR_INVALID_HANDLE);
790 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
791 AssertReturn(cbToWrite > 0, VERR_INVALID_PARAMETER);
792 AssertPtrReturn(pcbWritten, VERR_INVALID_POINTER);
793
794 *pcbWritten = 0;
795
796 int rc = VINF_SUCCESS;
797 ssize_t cbThisWrite = write(pThis->iFd, pvBuf, cbToWrite);
798 if (cbThisWrite > 0)
799 *pcbWritten = cbThisWrite;
800 else if (cbThisWrite == 0 || errno == EAGAIN || errno == EWOULDBLOCK)
801 rc = VINF_TRY_AGAIN;
802 else
803 rc = RTErrConvertFromErrno(errno);
804
805 return rc;
806}
807
808
809RTDECL(int) RTSerialPortCfgQueryCurrent(RTSERIALPORT hSerialPort, PRTSERIALPORTCFG pCfg)
810{
811 PRTSERIALPORTINTERNAL pThis = hSerialPort;
812 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
813 AssertReturn(pThis->u32Magic == RTSERIALPORT_MAGIC, VERR_INVALID_HANDLE);
814
815 return rtSerialPortTermios2Cfg(&pThis->PortCfg, pCfg);
816}
817
818
819RTDECL(int) RTSerialPortCfgSet(RTSERIALPORT hSerialPort, PCRTSERIALPORTCFG pCfg, PRTERRINFO pErrInfo)
820{
821 PRTSERIALPORTINTERNAL pThis = hSerialPort;
822 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
823 AssertReturn(pThis->u32Magic == RTSERIALPORT_MAGIC, VERR_INVALID_HANDLE);
824
825 struct termios PortCfgNew; RT_ZERO(PortCfgNew);
826 int rc = rtSerialPortCfg2Termios(pCfg, &PortCfgNew, pErrInfo);
827 if (RT_SUCCESS(rc))
828 {
829 int rcPsx = tcsetattr(pThis->iFd, TCSANOW, &PortCfgNew);
830 if (rcPsx == -1)
831 rc = RTErrConvertFromErrno(errno);
832 else
833 memcpy(&pThis->PortCfg, &PortCfgNew, sizeof(struct termios));
834
835#ifdef RT_OS_LINUX
836 /*
837 * XXX In Linux, if a thread calls tcsetattr while the monitor thread is
838 * waiting in ioctl for a modem status change then 8250.c wrongly disables
839 * modem irqs and so the monitor thread never gets released. The workaround
840 * is to send a signal after each tcsetattr.
841 */
842 if (pThis->fOpenFlags & RTSERIALPORT_OPEN_F_SUPPORT_STATUS_LINE_MONITORING)
843 RTThreadPoke(pThis->hMonThrd);
844#endif
845 }
846
847 return rc;
848}
849
850
851RTDECL(int) RTSerialPortEvtPoll(RTSERIALPORT hSerialPort, uint32_t fEvtMask, uint32_t *pfEvtsRecv,
852 RTMSINTERVAL msTimeout)
853{
854 PRTSERIALPORTINTERNAL pThis = hSerialPort;
855 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
856 AssertReturn(pThis->u32Magic == RTSERIALPORT_MAGIC, VERR_INVALID_HANDLE);
857 AssertReturn(!(fEvtMask & ~RTSERIALPORT_EVT_F_VALID_MASK), VERR_INVALID_PARAMETER);
858 AssertPtrReturn(pfEvtsRecv, VERR_INVALID_POINTER);
859
860 *pfEvtsRecv = 0;
861
862 fEvtMask |= RTSERIALPORT_EVT_F_STATUS_LINE_MONITOR_FAILED; /* This will be reported always, no matter what the caller wants. */
863
864 /* Return early if there are events pending from previous calls which weren't fetched yet. */
865 for (;;)
866 {
867 uint32_t fEvtsPending = ASMAtomicReadU32(&pThis->fEvtsPending);
868 if (fEvtsPending & fEvtMask)
869 {
870 *pfEvtsRecv = fEvtsPending & fEvtMask;
871 /* Write back, repeat the whole procedure if someone else raced us. */
872 if (ASMAtomicCmpXchgU32(&pThis->fEvtsPending, fEvtsPending & ~fEvtMask, fEvtsPending))
873 return VINF_SUCCESS;
874 }
875 else
876 break;
877 }
878
879 struct pollfd aPollFds[2]; RT_ZERO(aPollFds);
880 aPollFds[0].fd = pThis->iFd;
881 aPollFds[0].events = POLLERR | POLLHUP;
882 aPollFds[0].revents = 0;
883 if ( (pThis->fOpenFlags & RTSERIALPORT_OPEN_F_READ)
884 && (fEvtMask & RTSERIALPORT_EVT_F_DATA_RX))
885 aPollFds[0].events |= POLLIN;
886 if ( (pThis->fOpenFlags & RTSERIALPORT_OPEN_F_WRITE)
887 && (fEvtMask & RTSERIALPORT_EVT_F_DATA_TX))
888 aPollFds[0].events |= POLLOUT;
889
890 aPollFds[1].fd = pThis->iFdPipeR;
891 aPollFds[1].events = POLLIN | POLLERR | POLLHUP;
892 aPollFds[1].revents = 0;
893
894 int rcPsx = 0;
895 int msTimeoutLeft = msTimeout == RT_INDEFINITE_WAIT ? -1 : msTimeout;
896 while (msTimeoutLeft != 0)
897 {
898 uint64_t tsPollStart = RTTimeMilliTS();
899
900 rcPsx = poll(&aPollFds[0], RT_ELEMENTS(aPollFds), msTimeoutLeft);
901 if (rcPsx != -1 || errno != EINTR)
902 break;
903 /* Restart when getting interrupted. */
904 if (msTimeoutLeft > -1)
905 {
906 uint64_t tsPollEnd = RTTimeMilliTS();
907 uint64_t tsPollSpan = tsPollEnd - tsPollStart;
908 msTimeoutLeft -= RT_MIN(tsPollSpan, (uint32_t)msTimeoutLeft);
909 }
910 }
911
912 int rc = VINF_SUCCESS;
913 uint32_t fEvtsPending = 0;
914 if (rcPsx < 0 && errno != EINTR)
915 rc = RTErrConvertFromErrno(errno);
916 else if (rcPsx > 0)
917 {
918 if (aPollFds[0].revents != 0)
919 {
920 fEvtsPending |= (aPollFds[0].revents & POLLIN) ? RTSERIALPORT_EVT_F_DATA_RX : 0;
921 fEvtsPending |= (aPollFds[0].revents & POLLIN) ? RTSERIALPORT_EVT_F_DATA_TX : 0;
922 /** @todo BREAK condition detection. */
923 }
924
925 if (aPollFds[1].revents != 0)
926 {
927 AssertReturn(!(aPollFds[1].revents & (POLLHUP | POLLERR | POLLNVAL)), VERR_INTERNAL_ERROR);
928 Assert(aPollFds[1].revents & POLLIN);
929
930 uint8_t bWakeupReason = 0;
931 ssize_t cbRead = read(pThis->iFdPipeR, &bWakeupReason, 1);
932 if (cbRead == 1)
933 {
934 switch (bWakeupReason)
935 {
936 case RTSERIALPORT_WAKEUP_PIPE_REASON_INTERRUPT:
937 rc = VERR_INTERRUPTED;
938 break;
939 case RTSERIALPORT_WAKEUP_PIPE_REASON_STS_LINE_CHANGED:
940 fEvtsPending |= RTSERIALPORT_EVT_F_STATUS_LINE_CHANGED;
941 break;
942 case RTSERIALPORT_WAKEUP_PIPE_REASON_STS_LINE_MONITOR_FAILED:
943 fEvtsPending |= RTSERIALPORT_EVT_F_STATUS_LINE_MONITOR_FAILED;
944 break;
945 default:
946 AssertFailed();
947 rc = VERR_INTERNAL_ERROR;
948 }
949 }
950 else
951 rc = VERR_INTERNAL_ERROR;
952 }
953 }
954 else
955 rc = VERR_TIMEOUT;
956
957 *pfEvtsRecv = fEvtsPending & fEvtMask;
958 fEvtsPending &= ~fEvtMask;
959 ASMAtomicOrU32(&pThis->fEvtsPending, fEvtsPending);
960
961 return rc;
962}
963
964
965RTDECL(int) RTSerialPortEvtPollInterrupt(RTSERIALPORT hSerialPort)
966{
967 PRTSERIALPORTINTERNAL pThis = hSerialPort;
968 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
969 AssertReturn(pThis->u32Magic == RTSERIALPORT_MAGIC, VERR_INVALID_HANDLE);
970
971 return rtSerialPortWakeupEvtPoller(pThis, RTSERIALPORT_WAKEUP_PIPE_REASON_INTERRUPT);
972}
973
974
975RTDECL(int) RTSerialPortChgBreakCondition(RTSERIALPORT hSerialPort, bool fSet)
976{
977 PRTSERIALPORTINTERNAL pThis = hSerialPort;
978 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
979 AssertReturn(pThis->u32Magic == RTSERIALPORT_MAGIC, VERR_INVALID_HANDLE);
980
981 int rc = VINF_SUCCESS;
982 int rcPsx = ioctl(pThis->iFd, fSet ? TIOCSBRK : TIOCCBRK);
983 if (rcPsx == -1)
984 rc = RTErrConvertFromErrno(errno);
985
986 return rc;
987}
988
989
990RTDECL(int) RTSerialPortChgStatusLines(RTSERIALPORT hSerialPort, uint32_t fClear, uint32_t fSet)
991{
992 PRTSERIALPORTINTERNAL pThis = hSerialPort;
993 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
994 AssertReturn(pThis->u32Magic == RTSERIALPORT_MAGIC, VERR_INVALID_HANDLE);
995
996 int rc = VINF_SUCCESS;
997 int fTiocmSet = 0;
998 int fTiocmClear = 0;
999
1000 if (fClear & RTSERIALPORT_CHG_STS_LINES_F_RTS)
1001 fTiocmClear |= TIOCM_RTS;
1002 if (fClear & RTSERIALPORT_CHG_STS_LINES_F_DTR)
1003 fTiocmClear |= TIOCM_DTR;
1004
1005 if (fSet & RTSERIALPORT_CHG_STS_LINES_F_RTS)
1006 fTiocmSet |= TIOCM_RTS;
1007 if (fSet & RTSERIALPORT_CHG_STS_LINES_F_DTR)
1008 fTiocmSet |= TIOCM_DTR;
1009
1010 int rcPsx = ioctl(pThis->iFd, TIOCMBIS, &fTiocmSet);
1011 if (!rcPsx)
1012 {
1013 rcPsx = ioctl(pThis->iFd, TIOCMBIC, &fTiocmClear);
1014 if (rcPsx == -1)
1015 rc = RTErrConvertFromErrno(errno);
1016 }
1017 return rc;
1018}
1019
1020
1021RTDECL(int) RTSerialPortQueryStatusLines(RTSERIALPORT hSerialPort, uint32_t *pfStsLines)
1022{
1023 PRTSERIALPORTINTERNAL pThis = hSerialPort;
1024 AssertPtrReturn(pThis, VERR_INVALID_PARAMETER);
1025 AssertReturn(pThis->u32Magic == RTSERIALPORT_MAGIC, VERR_INVALID_HANDLE);
1026 AssertPtrReturn(pfStsLines, VERR_INVALID_POINTER);
1027
1028 *pfStsLines = 0;
1029
1030 int rc = VINF_SUCCESS;
1031 int fStsLines = 0;
1032 int rcPsx = ioctl(pThis->iFd, TIOCMGET, &fStsLines);
1033 if (!rcPsx)
1034 {
1035 /* This resets the status line event pending flag. */
1036 for (;;)
1037 {
1038 uint32_t fEvtsPending = ASMAtomicReadU32(&pThis->fEvtsPending);
1039 if (ASMAtomicCmpXchgU32(&pThis->fEvtsPending, fEvtsPending & ~RTSERIALPORT_EVT_F_STATUS_LINE_CHANGED, fEvtsPending))
1040 break;
1041 }
1042
1043 *pfStsLines |= (fStsLines & TIOCM_CAR) ? RTSERIALPORT_STS_LINE_DCD : 0;
1044 *pfStsLines |= (fStsLines & TIOCM_RNG) ? RTSERIALPORT_STS_LINE_RI : 0;
1045 *pfStsLines |= (fStsLines & TIOCM_DSR) ? RTSERIALPORT_STS_LINE_DSR : 0;
1046 *pfStsLines |= (fStsLines & TIOCM_CTS) ? RTSERIALPORT_STS_LINE_CTS : 0;
1047 }
1048 else
1049 rc = RTErrConvertFromErrno(errno);
1050
1051 return rc;
1052}
1053
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