]> sigrok.org Git - libserialport.git/blob - serialport.c
posix: Consistent debug output when blocking operations time out.
[libserialport.git] / serialport.c
1 /*
2  * This file is part of the libserialport project.
3  *
4  * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5  * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
6  * Copyright (C) 2013 Martin Ling <martin-libserialport@earth.li>
7  * Copyright (C) 2013 Matthias Heidbrink <m-sigrok@heidbrink.biz>
8  * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Lesser General Public License as
12  * published by the Free Software Foundation, either version 3 of the
13  * License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24 #include "libserialport.h"
25 #include "libserialport_internal.h"
26
27 static const struct std_baudrate std_baudrates[] = {
28 #ifdef _WIN32
29         /*
30          * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
31          * have documented CBR_* macros.
32          */
33         BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
34         BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
35         BAUD(115200), BAUD(128000), BAUD(256000),
36 #else
37         BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
38         BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
39         BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
40         BAUD(230400),
41 #if !defined(__APPLE__) && !defined(__OpenBSD__)
42         BAUD(460800),
43 #endif
44 #endif
45 };
46
47 #define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
48
49 void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
50
51 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
52         struct sp_port_config *config);
53
54 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
55         const struct sp_port_config *config);
56
57 SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
58 {
59         struct sp_port *port;
60 #ifndef NO_PORT_METADATA
61         enum sp_return ret;
62 #endif
63         int len;
64
65         TRACE("%s, %p", portname, port_ptr);
66
67         if (!port_ptr)
68                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
69
70         *port_ptr = NULL;
71
72         if (!portname)
73                 RETURN_ERROR(SP_ERR_ARG, "Null port name");
74
75         DEBUG_FMT("Building structure for port %s", portname);
76
77         if (!(port = malloc(sizeof(struct sp_port))))
78                 RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
79
80         len = strlen(portname) + 1;
81
82         if (!(port->name = malloc(len))) {
83                 free(port);
84                 RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
85         }
86
87         memcpy(port->name, portname, len);
88
89 #ifdef _WIN32
90         port->usb_path = NULL;
91         port->hdl = INVALID_HANDLE_VALUE;
92 #else
93         port->fd = -1;
94 #endif
95
96         port->description = NULL;
97         port->transport = SP_TRANSPORT_NATIVE;
98         port->usb_bus = -1;
99         port->usb_address = -1;
100         port->usb_vid = -1;
101         port->usb_pid = -1;
102         port->usb_manufacturer = NULL;
103         port->usb_product = NULL;
104         port->usb_serial = NULL;
105         port->bluetooth_address = NULL;
106
107 #ifndef NO_PORT_METADATA
108         if ((ret = get_port_details(port)) != SP_OK) {
109                 sp_free_port(port);
110                 return ret;
111         }
112 #endif
113
114         *port_ptr = port;
115
116         RETURN_OK();
117 }
118
119 SP_API char *sp_get_port_name(const struct sp_port *port)
120 {
121         TRACE("%p", port);
122
123         if (!port)
124                 return NULL;
125
126         RETURN_STRING(port->name);
127 }
128
129 SP_API char *sp_get_port_description(const struct sp_port *port)
130 {
131         TRACE("%p", port);
132
133         if (!port || !port->description)
134                 return NULL;
135
136         RETURN_STRING(port->description);
137 }
138
139 SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
140 {
141         TRACE("%p", port);
142
143         if (!port)
144                 RETURN_ERROR(SP_ERR_ARG, "Null port");
145
146         RETURN_INT(port->transport);
147 }
148
149 SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
150                                                   int *usb_bus,int *usb_address)
151 {
152         TRACE("%p", port);
153
154         if (!port)
155                 RETURN_ERROR(SP_ERR_ARG, "Null port");
156         if (port->transport != SP_TRANSPORT_USB)
157                 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
158         if (port->usb_bus < 0 || port->usb_address < 0)
159                 RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
160
161         if (usb_bus)
162                 *usb_bus = port->usb_bus;
163         if (usb_address)
164                 *usb_address = port->usb_address;
165
166         RETURN_OK();
167 }
168
169 SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
170                                               int *usb_vid, int *usb_pid)
171 {
172         TRACE("%p", port);
173
174         if (!port)
175                 RETURN_ERROR(SP_ERR_ARG, "Null port");
176         if (port->transport != SP_TRANSPORT_USB)
177                 RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
178         if (port->usb_vid < 0 || port->usb_pid < 0)
179                 RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
180
181         if (usb_vid)
182                 *usb_vid = port->usb_vid;
183         if (usb_pid)
184                 *usb_pid = port->usb_pid;
185
186         RETURN_OK();
187 }
188
189 SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
190 {
191         TRACE("%p", port);
192
193         if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
194                 return NULL;
195
196         RETURN_STRING(port->usb_manufacturer);
197 }
198
199 SP_API char *sp_get_port_usb_product(const struct sp_port *port)
200 {
201         TRACE("%p", port);
202
203         if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
204                 return NULL;
205
206         RETURN_STRING(port->usb_product);
207 }
208
209 SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
210 {
211         TRACE("%p", port);
212
213         if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
214                 return NULL;
215
216         RETURN_STRING(port->usb_serial);
217 }
218
219 SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
220 {
221         TRACE("%p", port);
222
223         if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
224             || !port->bluetooth_address)
225                 return NULL;
226
227         RETURN_STRING(port->bluetooth_address);
228 }
229
230 SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
231                                          void *result_ptr)
232 {
233         TRACE("%p, %p", port, result_ptr);
234
235         if (!port)
236                 RETURN_ERROR(SP_ERR_ARG, "Null port");
237         if (!result_ptr)
238                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
239
240 #ifdef _WIN32
241         HANDLE *handle_ptr = result_ptr;
242         *handle_ptr = port->hdl;
243 #else
244         int *fd_ptr = result_ptr;
245         *fd_ptr = port->fd;
246 #endif
247
248         RETURN_OK();
249 }
250
251 SP_API enum sp_return sp_copy_port(const struct sp_port *port,
252                                    struct sp_port **copy_ptr)
253 {
254         TRACE("%p, %p", port, copy_ptr);
255
256         if (!copy_ptr)
257                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
258
259         *copy_ptr = NULL;
260
261         if (!port)
262                 RETURN_ERROR(SP_ERR_ARG, "Null port");
263
264         if (!port->name)
265                 RETURN_ERROR(SP_ERR_ARG, "Null port name");
266
267         DEBUG("Copying port structure");
268
269         RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
270 }
271
272 SP_API void sp_free_port(struct sp_port *port)
273 {
274         TRACE("%p", port);
275
276         if (!port) {
277                 DEBUG("Null port");
278                 RETURN();
279         }
280
281         DEBUG("Freeing port structure");
282
283         if (port->name)
284                 free(port->name);
285         if (port->description)
286                 free(port->description);
287         if (port->usb_manufacturer)
288                 free(port->usb_manufacturer);
289         if (port->usb_product)
290                 free(port->usb_product);
291         if (port->usb_serial)
292                 free(port->usb_serial);
293         if (port->bluetooth_address)
294                 free(port->bluetooth_address);
295 #ifdef _WIN32
296         if (port->usb_path)
297                 free(port->usb_path);
298 #endif
299
300         free(port);
301
302         RETURN();
303 }
304
305 SP_PRIV struct sp_port **list_append(struct sp_port **list,
306                                      const char *portname)
307 {
308         void *tmp;
309         unsigned int count;
310
311         for (count = 0; list[count]; count++);
312         if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
313                 goto fail;
314         list = tmp;
315         if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
316                 goto fail;
317         list[count + 1] = NULL;
318         return list;
319
320 fail:
321         sp_free_port_list(list);
322         return NULL;
323 }
324
325 SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
326 {
327 #ifndef NO_ENUMERATION
328         struct sp_port **list;
329         int ret;
330 #endif
331
332         TRACE("%p", list_ptr);
333
334         if (!list_ptr)
335                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
336
337         *list_ptr = NULL;
338
339 #ifdef NO_ENUMERATION
340         RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
341 #else
342         DEBUG("Enumerating ports");
343
344         if (!(list = malloc(sizeof(struct sp_port *))))
345                 RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
346
347         list[0] = NULL;
348
349         ret = list_ports(&list);
350
351         if (ret == SP_OK) {
352                 *list_ptr = list;
353         } else {
354                 sp_free_port_list(list);
355                 *list_ptr = NULL;
356         }
357
358         RETURN_CODEVAL(ret);
359 #endif
360 }
361
362 SP_API void sp_free_port_list(struct sp_port **list)
363 {
364         unsigned int i;
365
366         TRACE("%p", list);
367
368         if (!list) {
369                 DEBUG("Null list");
370                 RETURN();
371         }
372
373         DEBUG("Freeing port list");
374
375         for (i = 0; list[i]; i++)
376                 sp_free_port(list[i]);
377         free(list);
378
379         RETURN();
380 }
381
382 #define CHECK_PORT() do { \
383         if (!port) \
384                 RETURN_ERROR(SP_ERR_ARG, "Null port"); \
385         if (!port->name) \
386                 RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
387 } while (0)
388 #ifdef _WIN32
389 #define CHECK_PORT_HANDLE() do { \
390         if (port->hdl == INVALID_HANDLE_VALUE) \
391                 RETURN_ERROR(SP_ERR_ARG, "Invalid port handle"); \
392 } while (0)
393 #else
394 #define CHECK_PORT_HANDLE() do { \
395         if (port->fd < 0) \
396                 RETURN_ERROR(SP_ERR_ARG, "Invalid port fd"); \
397 } while (0)
398 #endif
399 #define CHECK_OPEN_PORT() do { \
400         CHECK_PORT(); \
401         CHECK_PORT_HANDLE(); \
402 } while (0)
403
404 #ifdef WIN32
405 /** To be called after port receive buffer is emptied. */
406 static enum sp_return restart_wait(struct sp_port *port)
407 {
408         DWORD wait_result;
409
410         if (port->wait_running) {
411                 /* Check status of running wait operation. */
412                 if (GetOverlappedResult(port->hdl, &port->wait_ovl,
413                                 &wait_result, FALSE)) {
414                         DEBUG("Previous wait completed");
415                         port->wait_running = FALSE;
416                 } else if (GetLastError() == ERROR_IO_INCOMPLETE) {
417                         DEBUG("Previous wait still running");
418                         RETURN_OK();
419                 } else {
420                         RETURN_FAIL("GetOverlappedResult() failed");
421                 }
422         }
423
424         if (!port->wait_running) {
425                 /* Start new wait operation. */
426                 if (WaitCommEvent(port->hdl, &port->events,
427                                 &port->wait_ovl)) {
428                         DEBUG("New wait returned, events already pending");
429                 } else if (GetLastError() == ERROR_IO_PENDING) {
430                         DEBUG("New wait running in background");
431                         port->wait_running = TRUE;
432                 } else {
433                         RETURN_FAIL("WaitCommEvent() failed");
434                 }
435         }
436
437         RETURN_OK();
438 }
439 #endif
440
441 SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
442 {
443         struct port_data data;
444         struct sp_port_config config;
445         enum sp_return ret;
446
447         TRACE("%p, 0x%x", port, flags);
448
449         CHECK_PORT();
450
451         if (flags > SP_MODE_READ_WRITE)
452                 RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
453
454         DEBUG_FMT("Opening port %s", port->name);
455
456 #ifdef _WIN32
457         DWORD desired_access = 0, flags_and_attributes = 0, errors;
458         char *escaped_port_name;
459         COMSTAT status;
460
461         /* Prefix port name with '\\.\' to work with ports above COM9. */
462         if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
463                 RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
464         sprintf(escaped_port_name, "\\\\.\\%s", port->name);
465
466         /* Map 'flags' to the OS-specific settings. */
467         flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
468         if (flags & SP_MODE_READ)
469                 desired_access |= GENERIC_READ;
470         if (flags & SP_MODE_WRITE)
471                 desired_access |= GENERIC_WRITE;
472
473         port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
474                          OPEN_EXISTING, flags_and_attributes, 0);
475
476         free(escaped_port_name);
477
478         if (port->hdl == INVALID_HANDLE_VALUE)
479                 RETURN_FAIL("Port CreateFile() failed");
480
481         /* All timeouts initially disabled. */
482         port->timeouts.ReadIntervalTimeout = 0;
483         port->timeouts.ReadTotalTimeoutMultiplier = 0;
484         port->timeouts.ReadTotalTimeoutConstant = 0;
485         port->timeouts.WriteTotalTimeoutMultiplier = 0;
486         port->timeouts.WriteTotalTimeoutConstant = 0;
487
488         if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
489                 sp_close(port);
490                 RETURN_FAIL("SetCommTimeouts() failed");
491         }
492
493         /* Prepare OVERLAPPED structures. */
494 #define INIT_OVERLAPPED(ovl) do { \
495         memset(&port->ovl, 0, sizeof(port->ovl)); \
496         port->ovl.hEvent = INVALID_HANDLE_VALUE; \
497         if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
498                         == INVALID_HANDLE_VALUE) { \
499                 sp_close(port); \
500                 RETURN_FAIL(#ovl "CreateEvent() failed"); \
501         } \
502 } while (0)
503
504         INIT_OVERLAPPED(read_ovl);
505         INIT_OVERLAPPED(write_ovl);
506         INIT_OVERLAPPED(wait_ovl);
507
508         /* Set event mask for RX and error events. */
509         if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
510                 sp_close(port);
511                 RETURN_FAIL("SetCommMask() failed");
512         }
513
514         port->writing = FALSE;
515         port->wait_running = FALSE;
516
517         ret = restart_wait(port);
518
519         if (ret < 0) {
520                 sp_close(port);
521                 RETURN_CODEVAL(ret);
522         }
523 #else
524         int flags_local = O_NONBLOCK | O_NOCTTY;
525
526         /* Map 'flags' to the OS-specific settings. */
527         if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
528                 flags_local |= O_RDWR;
529         else if (flags & SP_MODE_READ)
530                 flags_local |= O_RDONLY;
531         else if (flags & SP_MODE_WRITE)
532                 flags_local |= O_WRONLY;
533
534         if ((port->fd = open(port->name, flags_local)) < 0)
535                 RETURN_FAIL("open() failed");
536 #endif
537
538         ret = get_config(port, &data, &config);
539
540         if (ret < 0) {
541                 sp_close(port);
542                 RETURN_CODEVAL(ret);
543         }
544
545         /* Set sane port settings. */
546 #ifdef _WIN32
547         data.dcb.fBinary = TRUE;
548         data.dcb.fDsrSensitivity = FALSE;
549         data.dcb.fErrorChar = FALSE;
550         data.dcb.fNull = FALSE;
551         data.dcb.fAbortOnError = FALSE;
552 #else
553         /* Turn off all fancy termios tricks, give us a raw channel. */
554         data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
555 #ifdef IUCLC
556         data.term.c_iflag &= ~IUCLC;
557 #endif
558         data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
559 #ifdef OLCUC
560         data.term.c_oflag &= ~OLCUC;
561 #endif
562 #ifdef NLDLY
563         data.term.c_oflag &= ~NLDLY;
564 #endif
565 #ifdef CRDLY
566         data.term.c_oflag &= ~CRDLY;
567 #endif
568 #ifdef TABDLY
569         data.term.c_oflag &= ~TABDLY;
570 #endif
571 #ifdef BSDLY
572         data.term.c_oflag &= ~BSDLY;
573 #endif
574 #ifdef VTDLY
575         data.term.c_oflag &= ~VTDLY;
576 #endif
577 #ifdef FFDLY
578         data.term.c_oflag &= ~FFDLY;
579 #endif
580 #ifdef OFILL
581         data.term.c_oflag &= ~OFILL;
582 #endif
583         data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
584         data.term.c_cc[VMIN] = 0;
585         data.term.c_cc[VTIME] = 0;
586
587         /* Ignore modem status lines; enable receiver; leave control lines alone on close. */
588         data.term.c_cflag |= (CLOCAL | CREAD | HUPCL);
589 #endif
590
591 #ifdef _WIN32
592         if (ClearCommError(port->hdl, &errors, &status) == 0)
593                 RETURN_FAIL("ClearCommError() failed");
594 #endif
595
596         ret = set_config(port, &data, &config);
597
598         if (ret < 0) {
599                 sp_close(port);
600                 RETURN_CODEVAL(ret);
601         }
602
603         RETURN_OK();
604 }
605
606 SP_API enum sp_return sp_close(struct sp_port *port)
607 {
608         TRACE("%p", port);
609
610         CHECK_OPEN_PORT();
611
612         DEBUG_FMT("Closing port %s", port->name);
613
614 #ifdef _WIN32
615         /* Returns non-zero upon success, 0 upon failure. */
616         if (CloseHandle(port->hdl) == 0)
617                 RETURN_FAIL("Port CloseHandle() failed");
618         port->hdl = INVALID_HANDLE_VALUE;
619
620         /* Close event handles for overlapped structures. */
621 #define CLOSE_OVERLAPPED(ovl) do { \
622         if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
623                 CloseHandle(port->ovl.hEvent) == 0) \
624                 RETURN_FAIL(# ovl "event CloseHandle() failed"); \
625 } while (0)
626         CLOSE_OVERLAPPED(read_ovl);
627         CLOSE_OVERLAPPED(write_ovl);
628         CLOSE_OVERLAPPED(wait_ovl);
629
630 #else
631         /* Returns 0 upon success, -1 upon failure. */
632         if (close(port->fd) == -1)
633                 RETURN_FAIL("close() failed");
634         port->fd = -1;
635 #endif
636
637         RETURN_OK();
638 }
639
640 SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
641 {
642         TRACE("%p, 0x%x", port, buffers);
643
644         CHECK_OPEN_PORT();
645
646         if (buffers > SP_BUF_BOTH)
647                 RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
648
649         const char *buffer_names[] = {"no", "input", "output", "both"};
650
651         DEBUG_FMT("Flushing %s buffers on port %s",
652                 buffer_names[buffers], port->name);
653
654 #ifdef _WIN32
655         DWORD flags = 0;
656         if (buffers & SP_BUF_INPUT)
657                 flags |= PURGE_RXCLEAR;
658         if (buffers & SP_BUF_OUTPUT)
659                 flags |= PURGE_TXCLEAR;
660
661         /* Returns non-zero upon success, 0 upon failure. */
662         if (PurgeComm(port->hdl, flags) == 0)
663                 RETURN_FAIL("PurgeComm() failed");
664
665         if (buffers & SP_BUF_INPUT)
666                 TRY(restart_wait(port));
667 #else
668         int flags = 0;
669         if (buffers == SP_BUF_BOTH)
670                 flags = TCIOFLUSH;
671         else if (buffers == SP_BUF_INPUT)
672                 flags = TCIFLUSH;
673         else if (buffers == SP_BUF_OUTPUT)
674                 flags = TCOFLUSH;
675
676         /* Returns 0 upon success, -1 upon failure. */
677         if (tcflush(port->fd, flags) < 0)
678                 RETURN_FAIL("tcflush() failed");
679 #endif
680         RETURN_OK();
681 }
682
683 SP_API enum sp_return sp_drain(struct sp_port *port)
684 {
685         TRACE("%p", port);
686
687         CHECK_OPEN_PORT();
688
689         DEBUG_FMT("Draining port %s", port->name);
690
691 #ifdef _WIN32
692         /* Returns non-zero upon success, 0 upon failure. */
693         if (FlushFileBuffers(port->hdl) == 0)
694                 RETURN_FAIL("FlushFileBuffers() failed");
695         RETURN_OK();
696 #else
697         int result;
698         while (1) {
699 #ifdef __ANDROID__
700                 int arg = 1;
701                 result = ioctl(port->fd, TCSBRK, &arg);
702 #else
703                 result = tcdrain(port->fd);
704 #endif
705                 if (result < 0) {
706                         if (errno == EINTR) {
707                                 DEBUG("tcdrain() was interrupted");
708                                 continue;
709                         } else {
710                                 RETURN_FAIL("tcdrain() failed");
711                         }
712                 } else {
713                         RETURN_OK();
714                 }
715         }
716 #endif
717 }
718
719 SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
720                                         size_t count, unsigned int timeout_ms)
721 {
722         TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
723
724         CHECK_OPEN_PORT();
725
726         if (!buf)
727                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
728
729         if (timeout_ms)
730                 DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
731                         count, port->name, timeout_ms);
732         else
733                 DEBUG_FMT("Writing %d bytes to port %s, no timeout",
734                         count, port->name);
735
736         if (count == 0)
737                 RETURN_INT(0);
738
739 #ifdef _WIN32
740         DWORD bytes_written = 0;
741         BOOL result;
742
743         /* Wait for previous non-blocking write to complete, if any. */
744         if (port->writing) {
745                 DEBUG("Waiting for previous write to complete");
746                 result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
747                 port->writing = 0;
748                 if (!result)
749                         RETURN_FAIL("Previous write failed to complete");
750                 DEBUG("Previous write completed");
751         }
752
753         /* Set timeout. */
754         if (port->timeouts.WriteTotalTimeoutConstant != timeout_ms) {
755                 port->timeouts.WriteTotalTimeoutConstant = timeout_ms;
756                 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
757                         RETURN_FAIL("SetCommTimeouts() failed");
758         }
759
760         /* Start write. */
761         if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
762                 DEBUG("Write completed immediately");
763                 RETURN_INT(count);
764         } else if (GetLastError() == ERROR_IO_PENDING) {
765                 DEBUG("Waiting for write to complete");
766                 if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0)
767                         RETURN_FAIL("GetOverlappedResult() failed");
768                 DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, count);
769                 RETURN_INT(bytes_written);
770         } else {
771                 RETURN_FAIL("WriteFile() failed");
772         }
773 #else
774         size_t bytes_written = 0;
775         unsigned char *ptr = (unsigned char *) buf;
776         struct timeval start, delta, now, end = {0, 0};
777         fd_set fds;
778         int result;
779
780         if (timeout_ms) {
781                 /* Get time at start of operation. */
782                 gettimeofday(&start, NULL);
783                 /* Define duration of timeout. */
784                 delta.tv_sec = timeout_ms / 1000;
785                 delta.tv_usec = (timeout_ms % 1000) * 1000;
786                 /* Calculate time at which we should give up. */
787                 timeradd(&start, &delta, &end);
788         }
789
790         FD_ZERO(&fds);
791         FD_SET(port->fd, &fds);
792
793         /* Loop until we have written the requested number of bytes. */
794         while (bytes_written < count) {
795                 /* Wait until space is available. */
796                 if (timeout_ms) {
797                         gettimeofday(&now, NULL);
798                         if (timercmp(&now, &end, >))
799                                 /* Timeout has expired. */
800                                 break;
801                         timersub(&end, &now, &delta);
802                 }
803                 result = select(port->fd + 1, NULL, &fds, NULL, timeout_ms ? &delta : NULL);
804                 if (result < 0) {
805                         if (errno == EINTR) {
806                                 DEBUG("select() call was interrupted, repeating");
807                                 continue;
808                         } else {
809                                 RETURN_FAIL("select() failed");
810                         }
811                 } else if (result == 0) {
812                         /* Timeout has expired. */
813                         break;
814                 }
815
816                 /* Do write. */
817                 result = write(port->fd, ptr, count - bytes_written);
818
819                 if (result < 0) {
820                         if (errno == EAGAIN)
821                                 /* This shouldn't happen because we did a select() first, but handle anyway. */
822                                 continue;
823                         else
824                                 /* This is an actual failure. */
825                                 RETURN_FAIL("write() failed");
826                 }
827
828                 bytes_written += result;
829                 ptr += result;
830         }
831
832         if (bytes_written < count)
833                 DEBUG("Write timed out");
834
835         RETURN_INT(bytes_written);
836 #endif
837 }
838
839 SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
840                                            const void *buf, size_t count)
841 {
842         TRACE("%p, %p, %d", port, buf, count);
843
844         CHECK_OPEN_PORT();
845
846         if (!buf)
847                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
848
849         DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
850
851         if (count == 0)
852                 RETURN_INT(0);
853
854 #ifdef _WIN32
855         DWORD written = 0;
856         BYTE *ptr = (BYTE *) buf;
857
858         /* Check whether previous write is complete. */
859         if (port->writing) {
860                 if (HasOverlappedIoCompleted(&port->write_ovl)) {
861                         DEBUG("Previous write completed");
862                         port->writing = 0;
863                 } else {
864                         DEBUG("Previous write not complete");
865                         /* Can't take a new write until the previous one finishes. */
866                         RETURN_INT(0);
867                 }
868         }
869
870         /* Set timeout. */
871         if (port->timeouts.WriteTotalTimeoutConstant != 0) {
872                 port->timeouts.WriteTotalTimeoutConstant = 0;
873                 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
874                         RETURN_FAIL("SetCommTimeouts() failed");
875         }
876
877         /*
878          * Keep writing data until the OS has to actually start an async IO
879          * for it. At that point we know the buffer is full.
880          */
881         while (written < count) {
882                 /* Copy first byte of user buffer. */
883                 port->pending_byte = *ptr++;
884
885                 /* Start asynchronous write. */
886                 if (WriteFile(port->hdl, &port->pending_byte, 1, NULL, &port->write_ovl) == 0) {
887                         if (GetLastError() == ERROR_IO_PENDING) {
888                                 if (HasOverlappedIoCompleted(&port->write_ovl)) {
889                                         DEBUG("Asynchronous write completed immediately");
890                                         port->writing = 0;
891                                         written++;
892                                         continue;
893                                 } else {
894                                         DEBUG("Asynchronous write running");
895                                         port->writing = 1;
896                                         RETURN_INT(++written);
897                                 }
898                         } else {
899                                 /* Actual failure of some kind. */
900                                 RETURN_FAIL("WriteFile() failed");
901                         }
902                 } else {
903                         DEBUG("Single byte written immediately");
904                         written++;
905                 }
906         }
907
908         DEBUG("All bytes written immediately");
909
910         RETURN_INT(written);
911 #else
912         /* Returns the number of bytes written, or -1 upon failure. */
913         ssize_t written = write(port->fd, buf, count);
914
915         if (written < 0)
916                 RETURN_FAIL("write() failed");
917         else
918                 RETURN_INT(written);
919 #endif
920 }
921
922 #ifdef _WIN32
923 /* Restart wait operation if buffer was emptied. */
924 static enum sp_return restart_wait_if_needed(struct sp_port *port, unsigned int bytes_read)
925 {
926         DWORD errors;
927         COMSTAT comstat;
928
929         if (bytes_read == 0)
930                 RETURN_OK();
931
932         if (ClearCommError(port->hdl, &errors, &comstat) == 0)
933                 RETURN_FAIL("ClearCommError() failed");
934
935         if (comstat.cbInQue == 0)
936                 TRY(restart_wait(port));
937
938         RETURN_OK();
939 }
940 #endif
941
942 SP_API enum sp_return sp_blocking_read(struct sp_port *port, void *buf,
943                                        size_t count, unsigned int timeout_ms)
944 {
945         TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
946
947         CHECK_OPEN_PORT();
948
949         if (!buf)
950                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
951
952         if (timeout_ms)
953                 DEBUG_FMT("Reading %d bytes from port %s, timeout %d ms",
954                         count, port->name, timeout_ms);
955         else
956                 DEBUG_FMT("Reading %d bytes from port %s, no timeout",
957                         count, port->name);
958
959         if (count == 0)
960                 RETURN_INT(0);
961
962 #ifdef _WIN32
963         DWORD bytes_read = 0;
964
965         /* Set timeout. */
966         if (port->timeouts.ReadIntervalTimeout != 0 ||
967                         port->timeouts.ReadTotalTimeoutConstant != timeout_ms) {
968                 port->timeouts.ReadIntervalTimeout = 0;
969                 port->timeouts.ReadTotalTimeoutConstant = timeout_ms;
970                 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
971                         RETURN_FAIL("SetCommTimeouts() failed");
972         }
973
974         /* Start read. */
975         if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl)) {
976                 DEBUG("Read completed immediately");
977                 bytes_read = count;
978         } else if (GetLastError() == ERROR_IO_PENDING) {
979                 DEBUG("Waiting for read to complete");
980                 if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
981                         RETURN_FAIL("GetOverlappedResult() failed");
982                 DEBUG_FMT("Read completed, %d/%d bytes read", bytes_read, count);
983         } else {
984                 RETURN_FAIL("ReadFile() failed");
985         }
986
987         TRY(restart_wait_if_needed(port, bytes_read));
988
989         RETURN_INT(bytes_read);
990
991 #else
992         size_t bytes_read = 0;
993         unsigned char *ptr = (unsigned char *) buf;
994         struct timeval start, delta, now, end = {0, 0};
995         fd_set fds;
996         int result;
997
998         if (timeout_ms) {
999                 /* Get time at start of operation. */
1000                 gettimeofday(&start, NULL);
1001                 /* Define duration of timeout. */
1002                 delta.tv_sec = timeout_ms / 1000;
1003                 delta.tv_usec = (timeout_ms % 1000) * 1000;
1004                 /* Calculate time at which we should give up. */
1005                 timeradd(&start, &delta, &end);
1006         }
1007
1008         FD_ZERO(&fds);
1009         FD_SET(port->fd, &fds);
1010
1011         /* Loop until we have the requested number of bytes. */
1012         while (bytes_read < count) {
1013                 /* Wait until data is available. */
1014                 if (timeout_ms) {
1015                         gettimeofday(&now, NULL);
1016                         if (timercmp(&now, &end, >))
1017                                 /* Timeout has expired. */
1018                                 break;
1019                         timersub(&end, &now, &delta);
1020                 }
1021                 result = select(port->fd + 1, &fds, NULL, NULL, timeout_ms ? &delta : NULL);
1022                 if (result < 0) {
1023                         if (errno == EINTR) {
1024                                 DEBUG("select() call was interrupted, repeating");
1025                                 continue;
1026                         } else {
1027                                 RETURN_FAIL("select() failed");
1028                         }
1029                 } else if (result == 0) {
1030                         /* Timeout has expired. */
1031                         break;
1032                 }
1033
1034                 /* Do read. */
1035                 result = read(port->fd, ptr, count - bytes_read);
1036
1037                 if (result < 0) {
1038                         if (errno == EAGAIN)
1039                                 /* This shouldn't happen because we did a select() first, but handle anyway. */
1040                                 continue;
1041                         else
1042                                 /* This is an actual failure. */
1043                                 RETURN_FAIL("read() failed");
1044                 }
1045
1046                 bytes_read += result;
1047                 ptr += result;
1048         }
1049
1050         if (bytes_read < count)
1051                 DEBUG("Read timed out");
1052
1053         RETURN_INT(bytes_read);
1054 #endif
1055 }
1056
1057 SP_API enum sp_return sp_nonblocking_read(struct sp_port *port, void *buf,
1058                                           size_t count)
1059 {
1060         TRACE("%p, %p, %d", port, buf, count);
1061
1062         CHECK_OPEN_PORT();
1063
1064         if (!buf)
1065                 RETURN_ERROR(SP_ERR_ARG, "Null buffer");
1066
1067         DEBUG_FMT("Reading up to %d bytes from port %s", count, port->name);
1068
1069 #ifdef _WIN32
1070         DWORD bytes_read;
1071
1072         /* Set timeout. */
1073         if (port->timeouts.ReadIntervalTimeout != MAXDWORD ||
1074                         port->timeouts.ReadTotalTimeoutConstant != 0) {
1075                 port->timeouts.ReadIntervalTimeout = MAXDWORD;
1076                 port->timeouts.ReadTotalTimeoutConstant = 0;
1077                 if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
1078                         RETURN_FAIL("SetCommTimeouts() failed");
1079         }
1080
1081         /* Do read. */
1082         if (ReadFile(port->hdl, buf, count, NULL, &port->read_ovl) == 0)
1083                 RETURN_FAIL("ReadFile() failed");
1084
1085         /* Get number of bytes read. */
1086         if (GetOverlappedResult(port->hdl, &port->read_ovl, &bytes_read, TRUE) == 0)
1087                 RETURN_FAIL("GetOverlappedResult() failed");
1088
1089         TRY(restart_wait_if_needed(port, bytes_read));
1090
1091         RETURN_INT(bytes_read);
1092 #else
1093         ssize_t bytes_read;
1094
1095         /* Returns the number of bytes read, or -1 upon failure. */
1096         if ((bytes_read = read(port->fd, buf, count)) < 0) {
1097                 if (errno == EAGAIN)
1098                         /* No bytes available. */
1099                         bytes_read = 0;
1100                 else
1101                         /* This is an actual failure. */
1102                         RETURN_FAIL("read() failed");
1103         }
1104         RETURN_INT(bytes_read);
1105 #endif
1106 }
1107
1108 SP_API enum sp_return sp_input_waiting(struct sp_port *port)
1109 {
1110         TRACE("%p", port);
1111
1112         CHECK_OPEN_PORT();
1113
1114         DEBUG_FMT("Checking input bytes waiting on port %s", port->name);
1115
1116 #ifdef _WIN32
1117         DWORD errors;
1118         COMSTAT comstat;
1119
1120         if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1121                 RETURN_FAIL("ClearCommError() failed");
1122         RETURN_INT(comstat.cbInQue);
1123 #else
1124         int bytes_waiting;
1125         if (ioctl(port->fd, TIOCINQ, &bytes_waiting) < 0)
1126                 RETURN_FAIL("TIOCINQ ioctl failed");
1127         RETURN_INT(bytes_waiting);
1128 #endif
1129 }
1130
1131 SP_API enum sp_return sp_output_waiting(struct sp_port *port)
1132 {
1133         TRACE("%p", port);
1134
1135         CHECK_OPEN_PORT();
1136
1137         DEBUG_FMT("Checking output bytes waiting on port %s", port->name);
1138
1139 #ifdef _WIN32
1140         DWORD errors;
1141         COMSTAT comstat;
1142
1143         if (ClearCommError(port->hdl, &errors, &comstat) == 0)
1144                 RETURN_FAIL("ClearCommError() failed");
1145         RETURN_INT(comstat.cbOutQue);
1146 #else
1147         int bytes_waiting;
1148         if (ioctl(port->fd, TIOCOUTQ, &bytes_waiting) < 0)
1149                 RETURN_FAIL("TIOCOUTQ ioctl failed");
1150         RETURN_INT(bytes_waiting);
1151 #endif
1152 }
1153
1154 SP_API enum sp_return sp_new_event_set(struct sp_event_set **result_ptr)
1155 {
1156         struct sp_event_set *result;
1157
1158         TRACE("%p", result_ptr);
1159
1160         if (!result_ptr)
1161                 RETURN_ERROR(SP_ERR_ARG, "Null result");
1162
1163         *result_ptr = NULL;
1164
1165         if (!(result = malloc(sizeof(struct sp_event_set))))
1166                 RETURN_ERROR(SP_ERR_MEM, "sp_event_set malloc() failed");
1167
1168         memset(result, 0, sizeof(struct sp_event_set));
1169
1170         *result_ptr = result;
1171
1172         RETURN_OK();
1173 }
1174
1175 static enum sp_return add_handle(struct sp_event_set *event_set,
1176                 event_handle handle, enum sp_event mask)
1177 {
1178         void *new_handles;
1179         enum sp_event *new_masks;
1180
1181         TRACE("%p, %d, %d", event_set, handle, mask);
1182
1183         if (!(new_handles = realloc(event_set->handles,
1184                         sizeof(event_handle) * (event_set->count + 1))))
1185                 RETURN_ERROR(SP_ERR_MEM, "Handle array realloc() failed");
1186
1187         event_set->handles = new_handles;
1188
1189         if (!(new_masks = realloc(event_set->masks,
1190                         sizeof(enum sp_event) * (event_set->count + 1))))
1191                 RETURN_ERROR(SP_ERR_MEM, "Mask array realloc() failed");
1192
1193         event_set->masks = new_masks;
1194
1195         ((event_handle *) event_set->handles)[event_set->count] = handle;
1196         event_set->masks[event_set->count] = mask;
1197
1198         event_set->count++;
1199
1200         RETURN_OK();
1201 }
1202
1203 SP_API enum sp_return sp_add_port_events(struct sp_event_set *event_set,
1204         const struct sp_port *port, enum sp_event mask)
1205 {
1206         TRACE("%p, %p, %d", event_set, port, mask);
1207
1208         if (!event_set)
1209                 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1210
1211         if (!port)
1212                 RETURN_ERROR(SP_ERR_ARG, "Null port");
1213
1214         if (mask > (SP_EVENT_RX_READY | SP_EVENT_TX_READY | SP_EVENT_ERROR))
1215                 RETURN_ERROR(SP_ERR_ARG, "Invalid event mask");
1216
1217         if (!mask)
1218                 RETURN_OK();
1219
1220 #ifdef _WIN32
1221         enum sp_event handle_mask;
1222         if ((handle_mask = mask & SP_EVENT_TX_READY))
1223                 TRY(add_handle(event_set, port->write_ovl.hEvent, handle_mask));
1224         if ((handle_mask = mask & (SP_EVENT_RX_READY | SP_EVENT_ERROR)))
1225                 TRY(add_handle(event_set, port->wait_ovl.hEvent, handle_mask));
1226 #else
1227         TRY(add_handle(event_set, port->fd, mask));
1228 #endif
1229
1230         RETURN_OK();
1231 }
1232
1233 SP_API void sp_free_event_set(struct sp_event_set *event_set)
1234 {
1235         TRACE("%p", event_set);
1236
1237         if (!event_set) {
1238                 DEBUG("Null event set");
1239                 RETURN();
1240         }
1241
1242         DEBUG("Freeing event set");
1243
1244         if (event_set->handles)
1245                 free(event_set->handles);
1246         if (event_set->masks)
1247                 free(event_set->masks);
1248
1249         free(event_set);
1250
1251         RETURN();
1252 }
1253
1254 SP_API enum sp_return sp_wait(struct sp_event_set *event_set,
1255                               unsigned int timeout_ms)
1256 {
1257         TRACE("%p, %d", event_set, timeout_ms);
1258
1259         if (!event_set)
1260                 RETURN_ERROR(SP_ERR_ARG, "Null event set");
1261
1262 #ifdef _WIN32
1263         if (WaitForMultipleObjects(event_set->count, event_set->handles, FALSE,
1264                         timeout_ms ? timeout_ms : INFINITE) == WAIT_FAILED)
1265                 RETURN_FAIL("WaitForMultipleObjects() failed");
1266
1267         RETURN_OK();
1268 #else
1269         struct timeval start, delta, now, end = {0, 0};
1270         int result, timeout_remaining_ms;
1271         struct pollfd *pollfds;
1272         unsigned int i;
1273
1274         if (!(pollfds = malloc(sizeof(struct pollfd) * event_set->count)))
1275                 RETURN_ERROR(SP_ERR_MEM, "pollfds malloc() failed");
1276
1277         for (i = 0; i < event_set->count; i++) {
1278                 pollfds[i].fd = ((int *) event_set->handles)[i];
1279                 pollfds[i].events = 0;
1280                 pollfds[i].revents = 0;
1281                 if (event_set->masks[i] & SP_EVENT_RX_READY)
1282                         pollfds[i].events |= POLLIN;
1283                 if (event_set->masks[i] & SP_EVENT_TX_READY)
1284                         pollfds[i].events |= POLLOUT;
1285                 if (event_set->masks[i] & SP_EVENT_ERROR)
1286                         pollfds[i].events |= POLLERR;
1287         }
1288
1289         if (timeout_ms) {
1290                 /* Get time at start of operation. */
1291                 gettimeofday(&start, NULL);
1292                 /* Define duration of timeout. */
1293                 delta.tv_sec = timeout_ms / 1000;
1294                 delta.tv_usec = (timeout_ms % 1000) * 1000;
1295                 /* Calculate time at which we should give up. */
1296                 timeradd(&start, &delta, &end);
1297         }
1298
1299         /* Loop until an event occurs. */
1300         while (1) {
1301                 if (timeout_ms) {
1302                         gettimeofday(&now, NULL);
1303                         if (timercmp(&now, &end, >)) {
1304                                 DEBUG("Wait timed out");
1305                                 break;
1306                         }
1307                         timersub(&end, &now, &delta);
1308                         timeout_remaining_ms = delta.tv_sec * 1000 + delta.tv_usec / 1000;
1309                 }
1310
1311                 result = poll(pollfds, event_set->count, timeout_ms ? timeout_remaining_ms : -1);
1312
1313                 if (result < 0) {
1314                         if (errno == EINTR) {
1315                                 DEBUG("poll() call was interrupted, repeating");
1316                                 continue;
1317                         } else {
1318                                 free(pollfds);
1319                                 RETURN_FAIL("poll() failed");
1320                         }
1321                 } else if (result == 0) {
1322                         DEBUG("poll() timed out");
1323                         break;
1324                 } else {
1325                         DEBUG("poll() completed");
1326                         break;
1327                 }
1328         }
1329
1330         free(pollfds);
1331         RETURN_OK();
1332 #endif
1333 }
1334
1335 #ifdef USE_TERMIOS_SPEED
1336 static enum sp_return get_baudrate(int fd, int *baudrate)
1337 {
1338         void *data;
1339
1340         TRACE("%d, %p", fd, baudrate);
1341
1342         DEBUG("Getting baud rate");
1343
1344         if (!(data = malloc(get_termios_size())))
1345                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1346
1347         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1348                 free(data);
1349                 RETURN_FAIL("Getting termios failed");
1350         }
1351
1352         *baudrate = get_termios_speed(data);
1353
1354         free(data);
1355
1356         RETURN_OK();
1357 }
1358
1359 static enum sp_return set_baudrate(int fd, int baudrate)
1360 {
1361         void *data;
1362
1363         TRACE("%d, %d", fd, baudrate);
1364
1365         DEBUG("Getting baud rate");
1366
1367         if (!(data = malloc(get_termios_size())))
1368                 RETURN_ERROR(SP_ERR_MEM, "termios malloc failed");
1369
1370         if (ioctl(fd, get_termios_get_ioctl(), data) < 0) {
1371                 free(data);
1372                 RETURN_FAIL("Getting termios failed");
1373         }
1374
1375         DEBUG("Setting baud rate");
1376
1377         set_termios_speed(data, baudrate);
1378
1379         if (ioctl(fd, get_termios_set_ioctl(), data) < 0) {
1380                 free(data);
1381                 RETURN_FAIL("Setting termios failed");
1382         }
1383
1384         free(data);
1385
1386         RETURN_OK();
1387 }
1388 #endif /* USE_TERMIOS_SPEED */
1389
1390 #ifdef USE_TERMIOX
1391 static enum sp_return get_flow(int fd, struct port_data *data)
1392 {
1393         void *termx;
1394
1395         TRACE("%d, %p", fd, data);
1396
1397         DEBUG("Getting advanced flow control");
1398
1399         if (!(termx = malloc(get_termiox_size())))
1400                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1401
1402         if (ioctl(fd, TCGETX, termx) < 0) {
1403                 free(termx);
1404                 RETURN_FAIL("Getting termiox failed");
1405         }
1406
1407         get_termiox_flow(termx, &data->rts_flow, &data->cts_flow,
1408                         &data->dtr_flow, &data->dsr_flow);
1409
1410         free(termx);
1411
1412         RETURN_OK();
1413 }
1414
1415 static enum sp_return set_flow(int fd, struct port_data *data)
1416 {
1417         void *termx;
1418
1419         TRACE("%d, %p", fd, data);
1420
1421         DEBUG("Getting advanced flow control");
1422
1423         if (!(termx = malloc(get_termiox_size())))
1424                 RETURN_ERROR(SP_ERR_MEM, "termiox malloc failed");
1425
1426         if (ioctl(fd, TCGETX, termx) < 0) {
1427                 free(termx);
1428                 RETURN_FAIL("Getting termiox failed");
1429         }
1430
1431         DEBUG("Setting advanced flow control");
1432
1433         set_termiox_flow(termx, data->rts_flow, data->cts_flow,
1434                         data->dtr_flow, data->dsr_flow);
1435
1436         if (ioctl(fd, TCSETX, termx) < 0) {
1437                 free(termx);
1438                 RETURN_FAIL("Setting termiox failed");
1439         }
1440
1441         free(termx);
1442
1443         RETURN_OK();
1444 }
1445 #endif /* USE_TERMIOX */
1446
1447 static enum sp_return get_config(struct sp_port *port, struct port_data *data,
1448         struct sp_port_config *config)
1449 {
1450         unsigned int i;
1451
1452         TRACE("%p, %p, %p", port, data, config);
1453
1454         DEBUG_FMT("Getting configuration for port %s", port->name);
1455
1456 #ifdef _WIN32
1457         if (!GetCommState(port->hdl, &data->dcb))
1458                 RETURN_FAIL("GetCommState() failed");
1459
1460         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1461                 if (data->dcb.BaudRate == std_baudrates[i].index) {
1462                         config->baudrate = std_baudrates[i].value;
1463                         break;
1464                 }
1465         }
1466
1467         if (i == NUM_STD_BAUDRATES)
1468                 /* BaudRate field can be either an index or a custom baud rate. */
1469                 config->baudrate = data->dcb.BaudRate;
1470
1471         config->bits = data->dcb.ByteSize;
1472
1473         if (data->dcb.fParity)
1474                 switch (data->dcb.Parity) {
1475                 case NOPARITY:
1476                         config->parity = SP_PARITY_NONE;
1477                         break;
1478                 case ODDPARITY:
1479                         config->parity = SP_PARITY_ODD;
1480                         break;
1481                 case EVENPARITY:
1482                         config->parity = SP_PARITY_EVEN;
1483                         break;
1484                 case MARKPARITY:
1485                         config->parity = SP_PARITY_MARK;
1486                         break;
1487                 case SPACEPARITY:
1488                         config->parity = SP_PARITY_SPACE;
1489                         break;
1490                 default:
1491                         config->parity = -1;
1492                 }
1493         else
1494                 config->parity = SP_PARITY_NONE;
1495
1496         switch (data->dcb.StopBits) {
1497         case ONESTOPBIT:
1498                 config->stopbits = 1;
1499                 break;
1500         case TWOSTOPBITS:
1501                 config->stopbits = 2;
1502                 break;
1503         default:
1504                 config->stopbits = -1;
1505         }
1506
1507         switch (data->dcb.fRtsControl) {
1508         case RTS_CONTROL_DISABLE:
1509                 config->rts = SP_RTS_OFF;
1510                 break;
1511         case RTS_CONTROL_ENABLE:
1512                 config->rts = SP_RTS_ON;
1513                 break;
1514         case RTS_CONTROL_HANDSHAKE:
1515                 config->rts = SP_RTS_FLOW_CONTROL;
1516                 break;
1517         default:
1518                 config->rts = -1;
1519         }
1520
1521         config->cts = data->dcb.fOutxCtsFlow ? SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1522
1523         switch (data->dcb.fDtrControl) {
1524         case DTR_CONTROL_DISABLE:
1525                 config->dtr = SP_DTR_OFF;
1526                 break;
1527         case DTR_CONTROL_ENABLE:
1528                 config->dtr = SP_DTR_ON;
1529                 break;
1530         case DTR_CONTROL_HANDSHAKE:
1531                 config->dtr = SP_DTR_FLOW_CONTROL;
1532                 break;
1533         default:
1534                 config->dtr = -1;
1535         }
1536
1537         config->dsr = data->dcb.fOutxDsrFlow ? SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1538
1539         if (data->dcb.fInX) {
1540                 if (data->dcb.fOutX)
1541                         config->xon_xoff = SP_XONXOFF_INOUT;
1542                 else
1543                         config->xon_xoff = SP_XONXOFF_IN;
1544         } else {
1545                 if (data->dcb.fOutX)
1546                         config->xon_xoff = SP_XONXOFF_OUT;
1547                 else
1548                         config->xon_xoff = SP_XONXOFF_DISABLED;
1549         }
1550
1551 #else // !_WIN32
1552
1553         if (tcgetattr(port->fd, &data->term) < 0)
1554                 RETURN_FAIL("tcgetattr() failed");
1555
1556         if (ioctl(port->fd, TIOCMGET, &data->controlbits) < 0)
1557                 RETURN_FAIL("TIOCMGET ioctl failed");
1558
1559 #ifdef USE_TERMIOX
1560         int ret = get_flow(port->fd, data);
1561
1562         if (ret == SP_ERR_FAIL && errno == EINVAL)
1563                 data->termiox_supported = 0;
1564         else if (ret < 0)
1565                 RETURN_CODEVAL(ret);
1566         else
1567                 data->termiox_supported = 1;
1568 #else
1569         data->termiox_supported = 0;
1570 #endif
1571
1572         for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1573                 if (cfgetispeed(&data->term) == std_baudrates[i].index) {
1574                         config->baudrate = std_baudrates[i].value;
1575                         break;
1576                 }
1577         }
1578
1579         if (i == NUM_STD_BAUDRATES) {
1580 #ifdef __APPLE__
1581                 config->baudrate = (int)data->term.c_ispeed;
1582 #elif defined(USE_TERMIOS_SPEED)
1583                 TRY(get_baudrate(port->fd, &config->baudrate));
1584 #else
1585                 config->baudrate = -1;
1586 #endif
1587         }
1588
1589         switch (data->term.c_cflag & CSIZE) {
1590         case CS8:
1591                 config->bits = 8;
1592                 break;
1593         case CS7:
1594                 config->bits = 7;
1595                 break;
1596         case CS6:
1597                 config->bits = 6;
1598                 break;
1599         case CS5:
1600                 config->bits = 5;
1601                 break;
1602         default:
1603                 config->bits = -1;
1604         }
1605
1606         if (!(data->term.c_cflag & PARENB) && (data->term.c_iflag & IGNPAR))
1607                 config->parity = SP_PARITY_NONE;
1608         else if (!(data->term.c_cflag & PARENB) || (data->term.c_iflag & IGNPAR))
1609                 config->parity = -1;
1610 #ifdef CMSPAR
1611         else if (data->term.c_cflag & CMSPAR)
1612                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_MARK : SP_PARITY_SPACE;
1613 #endif
1614         else
1615                 config->parity = (data->term.c_cflag & PARODD) ? SP_PARITY_ODD : SP_PARITY_EVEN;
1616
1617         config->stopbits = (data->term.c_cflag & CSTOPB) ? 2 : 1;
1618
1619         if (data->term.c_cflag & CRTSCTS) {
1620                 config->rts = SP_RTS_FLOW_CONTROL;
1621                 config->cts = SP_CTS_FLOW_CONTROL;
1622         } else {
1623                 if (data->termiox_supported && data->rts_flow)
1624                         config->rts = SP_RTS_FLOW_CONTROL;
1625                 else
1626                         config->rts = (data->controlbits & TIOCM_RTS) ? SP_RTS_ON : SP_RTS_OFF;
1627
1628                 config->cts = (data->termiox_supported && data->cts_flow) ?
1629                         SP_CTS_FLOW_CONTROL : SP_CTS_IGNORE;
1630         }
1631
1632         if (data->termiox_supported && data->dtr_flow)
1633                 config->dtr = SP_DTR_FLOW_CONTROL;
1634         else
1635                 config->dtr = (data->controlbits & TIOCM_DTR) ? SP_DTR_ON : SP_DTR_OFF;
1636
1637         config->dsr = (data->termiox_supported && data->dsr_flow) ?
1638                 SP_DSR_FLOW_CONTROL : SP_DSR_IGNORE;
1639
1640         if (data->term.c_iflag & IXOFF) {
1641                 if (data->term.c_iflag & IXON)
1642                         config->xon_xoff = SP_XONXOFF_INOUT;
1643                 else
1644                         config->xon_xoff = SP_XONXOFF_IN;
1645         } else {
1646                 if (data->term.c_iflag & IXON)
1647                         config->xon_xoff = SP_XONXOFF_OUT;
1648                 else
1649                         config->xon_xoff = SP_XONXOFF_DISABLED;
1650         }
1651 #endif
1652
1653         RETURN_OK();
1654 }
1655
1656 static enum sp_return set_config(struct sp_port *port, struct port_data *data,
1657         const struct sp_port_config *config)
1658 {
1659         unsigned int i;
1660 #ifdef __APPLE__
1661         BAUD_TYPE baud_nonstd;
1662
1663         baud_nonstd = B0;
1664 #endif
1665 #ifdef USE_TERMIOS_SPEED
1666         int baud_nonstd = 0;
1667 #endif
1668
1669         TRACE("%p, %p, %p", port, data, config);
1670
1671         DEBUG_FMT("Setting configuration for port %s", port->name);
1672
1673 #ifdef _WIN32
1674         if (config->baudrate >= 0) {
1675                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1676                         if (config->baudrate == std_baudrates[i].value) {
1677                                 data->dcb.BaudRate = std_baudrates[i].index;
1678                                 break;
1679                         }
1680                 }
1681
1682                 if (i == NUM_STD_BAUDRATES)
1683                         data->dcb.BaudRate = config->baudrate;
1684         }
1685
1686         if (config->bits >= 0)
1687                 data->dcb.ByteSize = config->bits;
1688
1689         if (config->parity >= 0) {
1690                 switch (config->parity) {
1691                 case SP_PARITY_NONE:
1692                         data->dcb.Parity = NOPARITY;
1693                         break;
1694                 case SP_PARITY_ODD:
1695                         data->dcb.Parity = ODDPARITY;
1696                         break;
1697                 case SP_PARITY_EVEN:
1698                         data->dcb.Parity = EVENPARITY;
1699                         break;
1700                 case SP_PARITY_MARK:
1701                         data->dcb.Parity = MARKPARITY;
1702                         break;
1703                 case SP_PARITY_SPACE:
1704                         data->dcb.Parity = SPACEPARITY;
1705                         break;
1706                 default:
1707                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1708                 }
1709         }
1710
1711         if (config->stopbits >= 0) {
1712                 switch (config->stopbits) {
1713                 /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
1714                 case 1:
1715                         data->dcb.StopBits = ONESTOPBIT;
1716                         break;
1717                 case 2:
1718                         data->dcb.StopBits = TWOSTOPBITS;
1719                         break;
1720                 default:
1721                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bit setting");
1722                 }
1723         }
1724
1725         if (config->rts >= 0) {
1726                 switch (config->rts) {
1727                 case SP_RTS_OFF:
1728                         data->dcb.fRtsControl = RTS_CONTROL_DISABLE;
1729                         break;
1730                 case SP_RTS_ON:
1731                         data->dcb.fRtsControl = RTS_CONTROL_ENABLE;
1732                         break;
1733                 case SP_RTS_FLOW_CONTROL:
1734                         data->dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
1735                         break;
1736                 default:
1737                         RETURN_ERROR(SP_ERR_ARG, "Invalid RTS setting");
1738                 }
1739         }
1740
1741         if (config->cts >= 0) {
1742                 switch (config->cts) {
1743                 case SP_CTS_IGNORE:
1744                         data->dcb.fOutxCtsFlow = FALSE;
1745                         break;
1746                 case SP_CTS_FLOW_CONTROL:
1747                         data->dcb.fOutxCtsFlow = TRUE;
1748                         break;
1749                 default:
1750                         RETURN_ERROR(SP_ERR_ARG, "Invalid CTS setting");
1751                 }
1752         }
1753
1754         if (config->dtr >= 0) {
1755                 switch (config->dtr) {
1756                 case SP_DTR_OFF:
1757                         data->dcb.fDtrControl = DTR_CONTROL_DISABLE;
1758                         break;
1759                 case SP_DTR_ON:
1760                         data->dcb.fDtrControl = DTR_CONTROL_ENABLE;
1761                         break;
1762                 case SP_DTR_FLOW_CONTROL:
1763                         data->dcb.fDtrControl = DTR_CONTROL_HANDSHAKE;
1764                         break;
1765                 default:
1766                         RETURN_ERROR(SP_ERR_ARG, "Invalid DTR setting");
1767                 }
1768         }
1769
1770         if (config->dsr >= 0) {
1771                 switch (config->dsr) {
1772                 case SP_DSR_IGNORE:
1773                         data->dcb.fOutxDsrFlow = FALSE;
1774                         break;
1775                 case SP_DSR_FLOW_CONTROL:
1776                         data->dcb.fOutxDsrFlow = TRUE;
1777                         break;
1778                 default:
1779                         RETURN_ERROR(SP_ERR_ARG, "Invalid DSR setting");
1780                 }
1781         }
1782
1783         if (config->xon_xoff >= 0) {
1784                 switch (config->xon_xoff) {
1785                 case SP_XONXOFF_DISABLED:
1786                         data->dcb.fInX = FALSE;
1787                         data->dcb.fOutX = FALSE;
1788                         break;
1789                 case SP_XONXOFF_IN:
1790                         data->dcb.fInX = TRUE;
1791                         data->dcb.fOutX = FALSE;
1792                         break;
1793                 case SP_XONXOFF_OUT:
1794                         data->dcb.fInX = FALSE;
1795                         data->dcb.fOutX = TRUE;
1796                         break;
1797                 case SP_XONXOFF_INOUT:
1798                         data->dcb.fInX = TRUE;
1799                         data->dcb.fOutX = TRUE;
1800                         break;
1801                 default:
1802                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
1803                 }
1804         }
1805
1806         if (!SetCommState(port->hdl, &data->dcb))
1807                 RETURN_FAIL("SetCommState() failed");
1808
1809 #else /* !_WIN32 */
1810
1811         int controlbits;
1812
1813         if (config->baudrate >= 0) {
1814                 for (i = 0; i < NUM_STD_BAUDRATES; i++) {
1815                         if (config->baudrate == std_baudrates[i].value) {
1816                                 if (cfsetospeed(&data->term, std_baudrates[i].index) < 0)
1817                                         RETURN_FAIL("cfsetospeed() failed");
1818
1819                                 if (cfsetispeed(&data->term, std_baudrates[i].index) < 0)
1820                                         RETURN_FAIL("cfsetispeed() failed");
1821                                 break;
1822                         }
1823                 }
1824
1825                 /* Non-standard baud rate */
1826                 if (i == NUM_STD_BAUDRATES) {
1827 #ifdef __APPLE__
1828                         /* Set "dummy" baud rate. */
1829                         if (cfsetspeed(&data->term, B9600) < 0)
1830                                 RETURN_FAIL("cfsetspeed() failed");
1831                         baud_nonstd = config->baudrate;
1832 #elif defined(USE_TERMIOS_SPEED)
1833                         baud_nonstd = 1;
1834 #else
1835                         RETURN_ERROR(SP_ERR_SUPP, "Non-standard baudrate not supported");
1836 #endif
1837                 }
1838         }
1839
1840         if (config->bits >= 0) {
1841                 data->term.c_cflag &= ~CSIZE;
1842                 switch (config->bits) {
1843                 case 8:
1844                         data->term.c_cflag |= CS8;
1845                         break;
1846                 case 7:
1847                         data->term.c_cflag |= CS7;
1848                         break;
1849                 case 6:
1850                         data->term.c_cflag |= CS6;
1851                         break;
1852                 case 5:
1853                         data->term.c_cflag |= CS5;
1854                         break;
1855                 default:
1856                         RETURN_ERROR(SP_ERR_ARG, "Invalid data bits setting");
1857                 }
1858         }
1859
1860         if (config->parity >= 0) {
1861                 data->term.c_iflag &= ~IGNPAR;
1862                 data->term.c_cflag &= ~(PARENB | PARODD);
1863 #ifdef CMSPAR
1864                 data->term.c_cflag &= ~CMSPAR;
1865 #endif
1866                 switch (config->parity) {
1867                 case SP_PARITY_NONE:
1868                         data->term.c_iflag |= IGNPAR;
1869                         break;
1870                 case SP_PARITY_EVEN:
1871                         data->term.c_cflag |= PARENB;
1872                         break;
1873                 case SP_PARITY_ODD:
1874                         data->term.c_cflag |= PARENB | PARODD;
1875                         break;
1876 #ifdef CMSPAR
1877                 case SP_PARITY_MARK:
1878                         data->term.c_cflag |= PARENB | PARODD;
1879                         data->term.c_cflag |= CMSPAR;
1880                         break;
1881                 case SP_PARITY_SPACE:
1882                         data->term.c_cflag |= PARENB;
1883                         data->term.c_cflag |= CMSPAR;
1884                         break;
1885 #else
1886                 case SP_PARITY_MARK:
1887                 case SP_PARITY_SPACE:
1888                         RETURN_ERROR(SP_ERR_SUPP, "Mark/space parity not supported");
1889 #endif
1890                 default:
1891                         RETURN_ERROR(SP_ERR_ARG, "Invalid parity setting");
1892                 }
1893         }
1894
1895         if (config->stopbits >= 0) {
1896                 data->term.c_cflag &= ~CSTOPB;
1897                 switch (config->stopbits) {
1898                 case 1:
1899                         data->term.c_cflag &= ~CSTOPB;
1900                         break;
1901                 case 2:
1902                         data->term.c_cflag |= CSTOPB;
1903                         break;
1904                 default:
1905                         RETURN_ERROR(SP_ERR_ARG, "Invalid stop bits setting");
1906                 }
1907         }
1908
1909         if (config->rts >= 0 || config->cts >= 0) {
1910                 if (data->termiox_supported) {
1911                         data->rts_flow = data->cts_flow = 0;
1912                         switch (config->rts) {
1913                         case SP_RTS_OFF:
1914                         case SP_RTS_ON:
1915                                 controlbits = TIOCM_RTS;
1916                                 if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1917                                         RETURN_FAIL("Setting RTS signal level failed");
1918                                 break;
1919                         case SP_RTS_FLOW_CONTROL:
1920                                 data->rts_flow = 1;
1921                                 break;
1922                         default:
1923                                 break;
1924                         }
1925                         if (config->cts == SP_CTS_FLOW_CONTROL)
1926                                 data->cts_flow = 1;
1927
1928                         if (data->rts_flow && data->cts_flow)
1929                                 data->term.c_iflag |= CRTSCTS;
1930                         else
1931                                 data->term.c_iflag &= ~CRTSCTS;
1932                 } else {
1933                         /* Asymmetric use of RTS/CTS not supported. */
1934                         if (data->term.c_iflag & CRTSCTS) {
1935                                 /* Flow control can only be disabled for both RTS & CTS together. */
1936                                 if (config->rts >= 0 && config->rts != SP_RTS_FLOW_CONTROL) {
1937                                         if (config->cts != SP_CTS_IGNORE)
1938                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1939                                 }
1940                                 if (config->cts >= 0 && config->cts != SP_CTS_FLOW_CONTROL) {
1941                                         if (config->rts <= 0 || config->rts == SP_RTS_FLOW_CONTROL)
1942                                                 RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be disabled together");
1943                                 }
1944                         } else {
1945                                 /* Flow control can only be enabled for both RTS & CTS together. */
1946                                 if (((config->rts == SP_RTS_FLOW_CONTROL) && (config->cts != SP_CTS_FLOW_CONTROL)) ||
1947                                         ((config->cts == SP_CTS_FLOW_CONTROL) && (config->rts != SP_RTS_FLOW_CONTROL)))
1948                                         RETURN_ERROR(SP_ERR_SUPP, "RTS & CTS flow control must be enabled together");
1949                         }
1950
1951                         if (config->rts >= 0) {
1952                                 if (config->rts == SP_RTS_FLOW_CONTROL) {
1953                                         data->term.c_iflag |= CRTSCTS;
1954                                 } else {
1955                                         controlbits = TIOCM_RTS;
1956                                         if (ioctl(port->fd, config->rts == SP_RTS_ON ? TIOCMBIS : TIOCMBIC,
1957                                                         &controlbits) < 0)
1958                                                 RETURN_FAIL("Setting RTS signal level failed");
1959                                 }
1960                         }
1961                 }
1962         }
1963
1964         if (config->dtr >= 0 || config->dsr >= 0) {
1965                 if (data->termiox_supported) {
1966                         data->dtr_flow = data->dsr_flow = 0;
1967                         switch (config->dtr) {
1968                         case SP_DTR_OFF:
1969                         case SP_DTR_ON:
1970                                 controlbits = TIOCM_DTR;
1971                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC, &controlbits) < 0)
1972                                         RETURN_FAIL("Setting DTR signal level failed");
1973                                 break;
1974                         case SP_DTR_FLOW_CONTROL:
1975                                 data->dtr_flow = 1;
1976                                 break;
1977                         default:
1978                                 break;
1979                         }
1980                         if (config->dsr == SP_DSR_FLOW_CONTROL)
1981                                 data->dsr_flow = 1;
1982                 } else {
1983                         /* DTR/DSR flow control not supported. */
1984                         if (config->dtr == SP_DTR_FLOW_CONTROL || config->dsr == SP_DSR_FLOW_CONTROL)
1985                                 RETURN_ERROR(SP_ERR_SUPP, "DTR/DSR flow control not supported");
1986
1987                         if (config->dtr >= 0) {
1988                                 controlbits = TIOCM_DTR;
1989                                 if (ioctl(port->fd, config->dtr == SP_DTR_ON ? TIOCMBIS : TIOCMBIC,
1990                                                 &controlbits) < 0)
1991                                         RETURN_FAIL("Setting DTR signal level failed");
1992                         }
1993                 }
1994         }
1995
1996         if (config->xon_xoff >= 0) {
1997                 data->term.c_iflag &= ~(IXON | IXOFF | IXANY);
1998                 switch (config->xon_xoff) {
1999                 case SP_XONXOFF_DISABLED:
2000                         break;
2001                 case SP_XONXOFF_IN:
2002                         data->term.c_iflag |= IXOFF;
2003                         break;
2004                 case SP_XONXOFF_OUT:
2005                         data->term.c_iflag |= IXON | IXANY;
2006                         break;
2007                 case SP_XONXOFF_INOUT:
2008                         data->term.c_iflag |= IXON | IXOFF | IXANY;
2009                         break;
2010                 default:
2011                         RETURN_ERROR(SP_ERR_ARG, "Invalid XON/XOFF setting");
2012                 }
2013         }
2014
2015         if (tcsetattr(port->fd, TCSANOW, &data->term) < 0)
2016                 RETURN_FAIL("tcsetattr() failed");
2017
2018 #ifdef __APPLE__
2019         if (baud_nonstd != B0) {
2020                 if (ioctl(port->fd, IOSSIOSPEED, &baud_nonstd) == -1)
2021                         RETURN_FAIL("IOSSIOSPEED ioctl failed");
2022                 /*
2023                  * Set baud rates in data->term to correct, but incompatible
2024                  * with tcsetattr() value, same as delivered by tcgetattr().
2025                  */
2026                 if (cfsetspeed(&data->term, baud_nonstd) < 0)
2027                         RETURN_FAIL("cfsetspeed() failed");
2028         }
2029 #elif defined(__linux__)
2030 #ifdef USE_TERMIOS_SPEED
2031         if (baud_nonstd)
2032                 TRY(set_baudrate(port->fd, config->baudrate));
2033 #endif
2034 #ifdef USE_TERMIOX
2035         if (data->termiox_supported)
2036                 TRY(set_flow(port->fd, data));
2037 #endif
2038 #endif
2039
2040 #endif /* !_WIN32 */
2041
2042         RETURN_OK();
2043 }
2044
2045 SP_API enum sp_return sp_new_config(struct sp_port_config **config_ptr)
2046 {
2047         struct sp_port_config *config;
2048
2049         TRACE("%p", config_ptr);
2050
2051         if (!config_ptr)
2052                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2053
2054         *config_ptr = NULL;
2055
2056         if (!(config = malloc(sizeof(struct sp_port_config))))
2057                 RETURN_ERROR(SP_ERR_MEM, "Config malloc failed");
2058
2059         config->baudrate = -1;
2060         config->bits = -1;
2061         config->parity = -1;
2062         config->stopbits = -1;
2063         config->rts = -1;
2064         config->cts = -1;
2065         config->dtr = -1;
2066         config->dsr = -1;
2067
2068         *config_ptr = config;
2069
2070         RETURN_OK();
2071 }
2072
2073 SP_API void sp_free_config(struct sp_port_config *config)
2074 {
2075         TRACE("%p", config);
2076
2077         if (!config)
2078                 DEBUG("Null config");
2079         else
2080                 free(config);
2081
2082         RETURN();
2083 }
2084
2085 SP_API enum sp_return sp_get_config(struct sp_port *port,
2086                                     struct sp_port_config *config)
2087 {
2088         struct port_data data;
2089
2090         TRACE("%p, %p", port, config);
2091
2092         CHECK_OPEN_PORT();
2093
2094         if (!config)
2095                 RETURN_ERROR(SP_ERR_ARG, "Null config");
2096
2097         TRY(get_config(port, &data, config));
2098
2099         RETURN_OK();
2100 }
2101
2102 SP_API enum sp_return sp_set_config(struct sp_port *port,
2103                                     const struct sp_port_config *config)
2104 {
2105         struct port_data data;
2106         struct sp_port_config prev_config;
2107
2108         TRACE("%p, %p", port, config);
2109
2110         CHECK_OPEN_PORT();
2111
2112         if (!config)
2113                 RETURN_ERROR(SP_ERR_ARG, "Null config");
2114
2115         TRY(get_config(port, &data, &prev_config));
2116         TRY(set_config(port, &data, config));
2117
2118         RETURN_OK();
2119 }
2120
2121 #define CREATE_ACCESSORS(x, type) \
2122 SP_API enum sp_return sp_set_##x(struct sp_port *port, type x) { \
2123         struct port_data data; \
2124         struct sp_port_config config; \
2125         TRACE("%p, %d", port, x); \
2126         CHECK_OPEN_PORT(); \
2127         TRY(get_config(port, &data, &config)); \
2128         config.x = x; \
2129         TRY(set_config(port, &data, &config)); \
2130         RETURN_OK(); \
2131 } \
2132 SP_API enum sp_return sp_get_config_##x(const struct sp_port_config *config, \
2133                                         type *x) { \
2134         TRACE("%p, %p", config, x); \
2135         if (!x) \
2136                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer"); \
2137         if (!config) \
2138                 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2139         *x = config->x; \
2140         RETURN_OK(); \
2141 } \
2142 SP_API enum sp_return sp_set_config_##x(struct sp_port_config *config, \
2143                                         type x) { \
2144         TRACE("%p, %d", config, x); \
2145         if (!config) \
2146                 RETURN_ERROR(SP_ERR_ARG, "Null config"); \
2147         config->x = x; \
2148         RETURN_OK(); \
2149 }
2150
2151 CREATE_ACCESSORS(baudrate, int)
2152 CREATE_ACCESSORS(bits, int)
2153 CREATE_ACCESSORS(parity, enum sp_parity)
2154 CREATE_ACCESSORS(stopbits, int)
2155 CREATE_ACCESSORS(rts, enum sp_rts)
2156 CREATE_ACCESSORS(cts, enum sp_cts)
2157 CREATE_ACCESSORS(dtr, enum sp_dtr)
2158 CREATE_ACCESSORS(dsr, enum sp_dsr)
2159 CREATE_ACCESSORS(xon_xoff, enum sp_xonxoff)
2160
2161 SP_API enum sp_return sp_set_config_flowcontrol(struct sp_port_config *config,
2162                                                 enum sp_flowcontrol flowcontrol)
2163 {
2164         if (!config)
2165                 RETURN_ERROR(SP_ERR_ARG, "Null configuration");
2166
2167         if (flowcontrol > SP_FLOWCONTROL_DTRDSR)
2168                 RETURN_ERROR(SP_ERR_ARG, "Invalid flow control setting");
2169
2170         if (flowcontrol == SP_FLOWCONTROL_XONXOFF)
2171                 config->xon_xoff = SP_XONXOFF_INOUT;
2172         else
2173                 config->xon_xoff = SP_XONXOFF_DISABLED;
2174
2175         if (flowcontrol == SP_FLOWCONTROL_RTSCTS) {
2176                 config->rts = SP_RTS_FLOW_CONTROL;
2177                 config->cts = SP_CTS_FLOW_CONTROL;
2178         } else {
2179                 if (config->rts == SP_RTS_FLOW_CONTROL)
2180                         config->rts = SP_RTS_ON;
2181                 config->cts = SP_CTS_IGNORE;
2182         }
2183
2184         if (flowcontrol == SP_FLOWCONTROL_DTRDSR) {
2185                 config->dtr = SP_DTR_FLOW_CONTROL;
2186                 config->dsr = SP_DSR_FLOW_CONTROL;
2187         } else {
2188                 if (config->dtr == SP_DTR_FLOW_CONTROL)
2189                         config->dtr = SP_DTR_ON;
2190                 config->dsr = SP_DSR_IGNORE;
2191         }
2192
2193         RETURN_OK();
2194 }
2195
2196 SP_API enum sp_return sp_set_flowcontrol(struct sp_port *port,
2197                                          enum sp_flowcontrol flowcontrol)
2198 {
2199         struct port_data data;
2200         struct sp_port_config config;
2201
2202         TRACE("%p, %d", port, flowcontrol);
2203
2204         CHECK_OPEN_PORT();
2205
2206         TRY(get_config(port, &data, &config));
2207
2208         TRY(sp_set_config_flowcontrol(&config, flowcontrol));
2209
2210         TRY(set_config(port, &data, &config));
2211
2212         RETURN_OK();
2213 }
2214
2215 SP_API enum sp_return sp_get_signals(struct sp_port *port,
2216                                      enum sp_signal *signals)
2217 {
2218         TRACE("%p, %p", port, signals);
2219
2220         CHECK_OPEN_PORT();
2221
2222         if (!signals)
2223                 RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
2224
2225         DEBUG_FMT("Getting control signals for port %s", port->name);
2226
2227         *signals = 0;
2228 #ifdef _WIN32
2229         DWORD bits;
2230         if (GetCommModemStatus(port->hdl, &bits) == 0)
2231                 RETURN_FAIL("GetCommModemStatus() failed");
2232         if (bits & MS_CTS_ON)
2233                 *signals |= SP_SIG_CTS;
2234         if (bits & MS_DSR_ON)
2235                 *signals |= SP_SIG_DSR;
2236         if (bits & MS_RLSD_ON)
2237                 *signals |= SP_SIG_DCD;
2238         if (bits & MS_RING_ON)
2239                 *signals |= SP_SIG_RI;
2240 #else
2241         int bits;
2242         if (ioctl(port->fd, TIOCMGET, &bits) < 0)
2243                 RETURN_FAIL("TIOCMGET ioctl failed");
2244         if (bits & TIOCM_CTS)
2245                 *signals |= SP_SIG_CTS;
2246         if (bits & TIOCM_DSR)
2247                 *signals |= SP_SIG_DSR;
2248         if (bits & TIOCM_CAR)
2249                 *signals |= SP_SIG_DCD;
2250         if (bits & TIOCM_RNG)
2251                 *signals |= SP_SIG_RI;
2252 #endif
2253         RETURN_OK();
2254 }
2255
2256 SP_API enum sp_return sp_start_break(struct sp_port *port)
2257 {
2258         TRACE("%p", port);
2259
2260         CHECK_OPEN_PORT();
2261 #ifdef _WIN32
2262         if (SetCommBreak(port->hdl) == 0)
2263                 RETURN_FAIL("SetCommBreak() failed");
2264 #else
2265         if (ioctl(port->fd, TIOCSBRK, 1) < 0)
2266                 RETURN_FAIL("TIOCSBRK ioctl failed");
2267 #endif
2268
2269         RETURN_OK();
2270 }
2271
2272 SP_API enum sp_return sp_end_break(struct sp_port *port)
2273 {
2274         TRACE("%p", port);
2275
2276         CHECK_OPEN_PORT();
2277 #ifdef _WIN32
2278         if (ClearCommBreak(port->hdl) == 0)
2279                 RETURN_FAIL("ClearCommBreak() failed");
2280 #else
2281         if (ioctl(port->fd, TIOCCBRK, 1) < 0)
2282                 RETURN_FAIL("TIOCCBRK ioctl failed");
2283 #endif
2284
2285         RETURN_OK();
2286 }
2287
2288 SP_API int sp_last_error_code(void)
2289 {
2290         TRACE_VOID();
2291 #ifdef _WIN32
2292         RETURN_INT(GetLastError());
2293 #else
2294         RETURN_INT(errno);
2295 #endif
2296 }
2297
2298 SP_API char *sp_last_error_message(void)
2299 {
2300         TRACE_VOID();
2301
2302 #ifdef _WIN32
2303         TCHAR *message;
2304         DWORD error = GetLastError();
2305
2306         DWORD length = FormatMessage(
2307                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
2308                 FORMAT_MESSAGE_FROM_SYSTEM |
2309                 FORMAT_MESSAGE_IGNORE_INSERTS,
2310                 NULL,
2311                 error,
2312                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
2313                 (LPTSTR) &message,
2314                 0, NULL );
2315
2316         if (length >= 2 && message[length - 2] == '\r')
2317                 message[length - 2] = '\0';
2318
2319         RETURN_STRING(message);
2320 #else
2321         RETURN_STRING(strerror(errno));
2322 #endif
2323 }
2324
2325 SP_API void sp_free_error_message(char *message)
2326 {
2327         TRACE("%s", message);
2328
2329 #ifdef _WIN32
2330         LocalFree(message);
2331 #else
2332         (void)message;
2333 #endif
2334
2335         RETURN();
2336 }
2337
2338 SP_API void sp_set_debug_handler(void (*handler)(const char *format, ...))
2339 {
2340         TRACE("%p", handler);
2341
2342         sp_debug_handler = handler;
2343
2344         RETURN();
2345 }
2346
2347 SP_API void sp_default_debug_handler(const char *format, ...)
2348 {
2349         va_list args;
2350         va_start(args, format);
2351         if (getenv("LIBSERIALPORT_DEBUG")) {
2352                 fputs("sp: ", stderr);
2353                 vfprintf(stderr, format, args);
2354         }
2355         va_end(args);
2356 }
2357
2358 SP_API int sp_get_major_package_version(void)
2359 {
2360         return SP_PACKAGE_VERSION_MAJOR;
2361 }
2362
2363 SP_API int sp_get_minor_package_version(void)
2364 {
2365         return SP_PACKAGE_VERSION_MINOR;
2366 }
2367
2368 SP_API int sp_get_micro_package_version(void)
2369 {
2370         return SP_PACKAGE_VERSION_MICRO;
2371 }
2372
2373 SP_API const char *sp_get_package_version_string(void)
2374 {
2375         return SP_PACKAGE_VERSION_STRING;
2376 }
2377
2378 SP_API int sp_get_current_lib_version(void)
2379 {
2380         return SP_LIB_VERSION_CURRENT;
2381 }
2382
2383 SP_API int sp_get_revision_lib_version(void)
2384 {
2385         return SP_LIB_VERSION_REVISION;
2386 }
2387
2388 SP_API int sp_get_age_lib_version(void)
2389 {
2390         return SP_LIB_VERSION_AGE;
2391 }
2392
2393 SP_API const char *sp_get_lib_version_string(void)
2394 {
2395         return SP_LIB_VERSION_STRING;
2396 }
2397
2398 /** @} */