serial.c 15 KB
Newer Older
1 2 3 4
/*
 * This file is part of the flashrom project.
 *
 * Copyright (C) 2009 Urja Rannikko <urjaman@gmail.com>
5
 * Copyright (C) 2009,2010 Carl-Daniel Hailfinger
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 */

22 23
#include "platform.h"

24 25 26 27 28 29 30 31 32
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <inttypes.h>
33
#if IS_WINDOWS
Patrick Georgi's avatar
Patrick Georgi committed
34 35
#include <conio.h>
#else
36
#include <termios.h>
37 38 39
#include <unistd.h>
#include <sys/types.h>
#include <sys/ioctl.h>
Patrick Georgi's avatar
Patrick Georgi committed
40
#endif
41 42
#include "flash.h"
#include "programmer.h"
43

44
fdtype sp_fd = SER_INV_FD;
45

46
#if IS_WINDOWS
47 48 49 50 51 52
struct baudentry {
	DWORD flag;
	unsigned int baud;
};
#define BAUDENTRY(baud) { CBR_##baud, baud },
#else
53 54 55 56 57
struct baudentry {
	int flag;
	unsigned int baud;
};
#define BAUDENTRY(baud) { B##baud, baud },
58 59 60 61 62
#endif

/* I'd like if the C preprocessor could have directives in macros.
 * See TERMIOS(3) and http://msdn.microsoft.com/en-us/library/windows/desktop/aa363214(v=vs.85).aspx and
 * http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=blob;f=include/uapi/asm-generic/termbits.h */
63
static const struct baudentry sp_baudtable[] = {
64 65
	BAUDENTRY(9600) /* unconditional default */
#if defined(B19200) || defined(CBR_19200)
66
	BAUDENTRY(19200)
67 68
#endif
#if defined(B38400) || defined(CBR_38400)
69
	BAUDENTRY(38400)
70 71
#endif
#if defined(B57600) || defined(CBR_57600)
72
	BAUDENTRY(57600)
73 74
#endif
#if defined(B115200) || defined(CBR_115200)
75
	BAUDENTRY(115200)
76 77
#endif
#if defined(B230400) || defined(CBR_230400)
78 79
	BAUDENTRY(230400)
#endif
80
#if defined(B460800) || defined(CBR_460800)
81 82
	BAUDENTRY(460800)
#endif
83
#if defined(B500000) || defined(CBR_500000)
84 85
	BAUDENTRY(500000)
#endif
86
#if defined(B576000) || defined(CBR_576000)
87 88
	BAUDENTRY(576000)
#endif
89
#if defined(B921600) || defined(CBR_921600)
90 91
	BAUDENTRY(921600)
#endif
92
#if defined(B1000000) || defined(CBR_1000000)
93 94
	BAUDENTRY(1000000)
#endif
95
#if defined(B1152000) || defined(CBR_1152000)
96 97
	BAUDENTRY(1152000)
#endif
98
#if defined(B1500000) || defined(CBR_1500000)
99 100
	BAUDENTRY(1500000)
#endif
101
#if defined(B2000000) || defined(CBR_2000000)
102 103
	BAUDENTRY(2000000)
#endif
104
#if defined(B2500000) || defined(CBR_2500000)
105 106
	BAUDENTRY(2500000)
#endif
107
#if defined(B3000000) || defined(CBR_3000000)
108 109
	BAUDENTRY(3000000)
#endif
110
#if defined(B3500000) || defined(CBR_3500000)
111 112
	BAUDENTRY(3500000)
#endif
113
#if defined(B4000000) || defined(CBR_4000000)
114 115 116 117
	BAUDENTRY(4000000)
#endif
	{0, 0}			/* Terminator */
};
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

const struct baudentry *round_baud(unsigned int baud)
{
	int i;
	/* Round baud rate to next lower entry in sp_baudtable if it exists, else use the lowest entry. */
	for (i = ARRAY_SIZE(sp_baudtable) - 2; i >= 0 ; i--) {
		if (sp_baudtable[i].baud == baud)
			return &sp_baudtable[i];

		if (sp_baudtable[i].baud < baud) {
			msg_pinfo("Warning: given baudrate %d rounded down to %d.\n",
				  baud, sp_baudtable[i].baud);
			return &sp_baudtable[i];
		}
	}
	return &sp_baudtable[0];
}
135

136 137 138 139 140 141
/* Uses msg_perr to print the last system error.
 * Prints "Error: " followed first by \c msg and then by the description of the last error retrieved via
 * strerror() or FormatMessage() and ending with a linebreak. */
static void msg_perr_strerror(const char *msg)
{
	msg_perr("Error: %s", msg);
142
#if IS_WINDOWS
143 144 145 146 147 148 149 150 151 152 153 154 155 156
	char *lpMsgBuf;
	DWORD nErr = GetLastError();
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, nErr,
		      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL);
	msg_perr(lpMsgBuf);
	/* At least some formatted messages contain a line break at the end. Make sure to always print one */
	if (lpMsgBuf[strlen(lpMsgBuf)-1] != '\n')
		msg_perr("\n");
	LocalFree(lpMsgBuf);
#else
	msg_perr("%s\n", strerror(errno));
#endif
}

Stefan Tauner's avatar
Stefan Tauner committed
157
int serialport_config(fdtype fd, unsigned int baud)
158
{
Stefan Tauner's avatar
Stefan Tauner committed
159 160 161
	if (fd == SER_INV_FD) {
		msg_perr("%s: File descriptor is invalid.\n", __func__);
		return 1;
Patrick Georgi's avatar
Patrick Georgi committed
162
	}
Stefan Tauner's avatar
Stefan Tauner committed
163

164
#if IS_WINDOWS
Patrick Georgi's avatar
Patrick Georgi committed
165 166
	DCB dcb;
	if (!GetCommState(fd, &dcb)) {
Stefan Tauner's avatar
Stefan Tauner committed
167
		msg_perr_strerror("Could not fetch original serial port configuration: ");
Stefan Tauner's avatar
Stefan Tauner committed
168
		return 1;
Patrick Georgi's avatar
Patrick Georgi committed
169
	}
170
	const struct baudentry *entry = round_baud(baud);
171
	dcb.BaudRate = entry->flag;
172 173 174
	dcb.ByteSize = 8;
	dcb.Parity = NOPARITY;
	dcb.StopBits = ONESTOPBIT;
Patrick Georgi's avatar
Patrick Georgi committed
175
	if (!SetCommState(fd, &dcb)) {
176
		msg_perr_strerror("Could not change serial port configuration: ");
Stefan Tauner's avatar
Stefan Tauner committed
177
		return 1;
Patrick Georgi's avatar
Patrick Georgi committed
178
	}
179
	if (!GetCommState(fd, &dcb)) {
Stefan Tauner's avatar
Stefan Tauner committed
180
		msg_perr_strerror("Could not fetch new serial port configuration: ");
Stefan Tauner's avatar
Stefan Tauner committed
181
		return 1;
182 183
	}
	msg_pdbg("Baud rate is %ld.\n", dcb.BaudRate);
Patrick Georgi's avatar
Patrick Georgi committed
184
#else
Stefan Tauner's avatar
Stefan Tauner committed
185 186 187
	struct termios wanted, observed;
	if (tcgetattr(fd, &observed) != 0) {
		msg_perr_strerror("Could not fetch original serial port configuration: ");
Stefan Tauner's avatar
Stefan Tauner committed
188
		return 1;
Stefan Tauner's avatar
Stefan Tauner committed
189 190
	}
	wanted = observed;
191
	const struct baudentry *entry = round_baud(baud);
Stefan Tauner's avatar
Stefan Tauner committed
192 193
	if (cfsetispeed(&wanted, entry->flag) != 0 || cfsetospeed(&wanted, entry->flag) != 0) {
		msg_perr_strerror("Could not set serial baud rate: ");
Stefan Tauner's avatar
Stefan Tauner committed
194
		return 1;
Stefan Tauner's avatar
Stefan Tauner committed
195 196 197 198 199 200 201 202
	}
	wanted.c_cflag &= ~(PARENB | CSTOPB | CSIZE | CRTSCTS);
	wanted.c_cflag |= (CS8 | CLOCAL | CREAD);
	wanted.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
	wanted.c_iflag &= ~(IXON | IXOFF | IXANY | ICRNL | IGNCR | INLCR);
	wanted.c_oflag &= ~OPOST;
	if (tcsetattr(fd, TCSANOW, &wanted) != 0) {
		msg_perr_strerror("Could not change serial port configuration: ");
Stefan Tauner's avatar
Stefan Tauner committed
203
		return 1;
Stefan Tauner's avatar
Stefan Tauner committed
204 205 206
	}
	if (tcgetattr(fd, &observed) != 0) {
		msg_perr_strerror("Could not fetch new serial port configuration: ");
Stefan Tauner's avatar
Stefan Tauner committed
207
		return 1;
Stefan Tauner's avatar
Stefan Tauner committed
208 209 210 211
	}
	if (observed.c_cflag != wanted.c_cflag ||
	    observed.c_lflag != wanted.c_lflag ||
	    observed.c_iflag != wanted.c_iflag ||
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
	    observed.c_oflag != wanted.c_oflag) {
		msg_pwarn("Some requested serial options did not stick, continuing anyway.\n");
		msg_pdbg("          observed    wanted\n"
			 "c_cflag:  0x%08lX  0x%08lX\n"
			 "c_lflag:  0x%08lX  0x%08lX\n"
			 "c_iflag:  0x%08lX  0x%08lX\n"
			 "c_oflag:  0x%08lX  0x%08lX\n",
			 (long)observed.c_cflag, (long)wanted.c_cflag,
			 (long)observed.c_lflag, (long)wanted.c_lflag,
			 (long)observed.c_iflag, (long)wanted.c_iflag,
			 (long)observed.c_oflag, (long)wanted.c_oflag
			);
	}
	if (cfgetispeed(&observed) != cfgetispeed(&wanted) ||
	    cfgetospeed(&observed) != cfgetospeed(&wanted)) {
		msg_pwarn("Could not set baud rates exactly.\n");
		msg_pdbg("Actual baud flags are: ispeed: 0x%08lX, ospeed: 0x%08lX\n",
			  (long)cfgetispeed(&observed), (long)cfgetospeed(&observed));
Stefan Tauner's avatar
Stefan Tauner committed
230
	}
Stefan Tauner's avatar
Stefan Tauner committed
231 232 233
#endif
	return 0;
}
Stefan Tauner's avatar
Stefan Tauner committed
234

Stefan Tauner's avatar
Stefan Tauner committed
235 236 237
fdtype sp_openserport(char *dev, unsigned int baud)
{
	fdtype fd;
238
#if IS_WINDOWS
Stefan Tauner's avatar
Stefan Tauner committed
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
	char *dev2 = dev;
	if ((strlen(dev) > 3) &&
	    (tolower((unsigned char)dev[0]) == 'c') &&
	    (tolower((unsigned char)dev[1]) == 'o') &&
	    (tolower((unsigned char)dev[2]) == 'm')) {
		dev2 = malloc(strlen(dev) + 5);
		if (!dev2) {
			msg_perr_strerror("Out of memory: ");
			return SER_INV_FD;
		}
		strcpy(dev2, "\\\\.\\");
		strcpy(dev2 + 4, dev);
	}
	fd = CreateFile(dev2, GENERIC_READ | GENERIC_WRITE, 0, NULL,
			OPEN_EXISTING, 0, NULL);
	if (dev2 != dev)
		free(dev2);
	if (fd == INVALID_HANDLE_VALUE) {
		msg_perr_strerror("Cannot open serial port: ");
		return SER_INV_FD;
	}
	if (serialport_config(fd, baud) != 0) {
		CloseHandle(fd);
		return SER_INV_FD;
	}
	return fd;
#else
266
	fd = open(dev, O_RDWR | O_NOCTTY | O_NDELAY); // Use O_NDELAY to ignore DCD state
Stefan Tauner's avatar
Stefan Tauner committed
267 268 269 270
	if (fd < 0) {
		msg_perr_strerror("Cannot open serial port: ");
		return SER_INV_FD;
	}
271 272 273 274 275 276 277 278 279 280 281 282

	/* Ensure that we use blocking I/O */
	const int flags = fcntl(fd, F_GETFL);
	if (flags == -1) {
		msg_perr_strerror("Could not get serial port mode: ");
		return SER_INV_FD;
	}
	if (fcntl(fd, F_SETFL, flags & ~O_NONBLOCK) != 0) {
		msg_perr_strerror("Could not set serial port mode to blocking: ");
		return SER_INV_FD;
	}

Stefan Tauner's avatar
Stefan Tauner committed
283 284 285 286 287
	if (serialport_config(fd, baud) != 0) {
		close(fd);
		return SER_INV_FD;
	}
	return fd;
Patrick Georgi's avatar
Patrick Georgi committed
288
#endif
289 290
}

291
void sp_set_pin(enum SP_PIN pin, int val) {
292
#if IS_WINDOWS
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
	DWORD ctl;

	if(pin == PIN_TXD) {
		ctl = val ? SETBREAK: CLRBREAK;
	}
	else if(pin == PIN_DTR) {
		ctl = val ? SETDTR: CLRDTR;
	}
	else {
		ctl = val ? SETRTS: CLRRTS;
	}
	EscapeCommFunction(sp_fd, ctl);
#else
	int ctl, s;

	if(pin == PIN_TXD) {
		ioctl(sp_fd, val ? TIOCSBRK : TIOCCBRK, 0);
	}
	else {
		s = (pin == PIN_DTR) ? TIOCM_DTR : TIOCM_RTS;
		ioctl(sp_fd, TIOCMGET, &ctl);

		if (val) {
			ctl |= s;
		}
		else {
			ctl &= ~s;
		}
		ioctl(sp_fd, TIOCMSET, &ctl);
	}
#endif
}

int sp_get_pin(enum SP_PIN pin) {
	int s;
328
#if IS_WINDOWS
329 330 331 332 333 334 335 336 337 338 339 340 341 342
	DWORD ctl;

	s = (pin == PIN_CTS) ? MS_CTS_ON : MS_DSR_ON;
	GetCommModemStatus(sp_fd, &ctl);
#else
	int ctl;
	s = (pin == PIN_CTS) ? TIOCM_CTS : TIOCM_DSR;
	ioctl(sp_fd, TIOCMGET, &ctl);
#endif

	return ((ctl & s) ? 1 : 0);

}

343 344
void sp_flush_incoming(void)
{
345
#if IS_WINDOWS
Patrick Georgi's avatar
Patrick Georgi committed
346 347
	PurgeComm(sp_fd, PURGE_RXCLEAR);
#else
348
	/* FIXME: error handling */
Patrick Georgi's avatar
Patrick Georgi committed
349
	tcflush(sp_fd, TCIFLUSH);
Patrick Georgi's avatar
Patrick Georgi committed
350
#endif
351 352
	return;
}
353

354
int serialport_shutdown(void *data)
355
{
356
#if IS_WINDOWS
Patrick Georgi's avatar
Patrick Georgi committed
357 358
	CloseHandle(sp_fd);
#else
359
	close(sp_fd);
Patrick Georgi's avatar
Patrick Georgi committed
360
#endif
361 362 363
	return 0;
}

364
int serialport_write(const unsigned char *buf, unsigned int writecnt)
365
{
366
#if IS_WINDOWS
367 368 369 370
	DWORD tmp = 0;
#else
	ssize_t tmp = 0;
#endif
371
	unsigned int empty_writes = 250; /* results in a ca. 125ms timeout */
372

Patrick Georgi's avatar
Patrick Georgi committed
373
	while (writecnt > 0) {
374
#if IS_WINDOWS
Patrick Georgi's avatar
Patrick Georgi committed
375 376
		WriteFile(sp_fd, buf, writecnt, &tmp, NULL);
#else
Patrick Georgi's avatar
Patrick Georgi committed
377
		tmp = write(sp_fd, buf, writecnt);
Patrick Georgi's avatar
Patrick Georgi committed
378
#endif
379 380
		if (tmp == -1) {
			msg_perr("Serial port write error!\n");
381
			return 1;
382
		}
383 384 385
		if (!tmp) {
			msg_pdbg2("Empty write\n");
			empty_writes--;
386
			internal_delay(500);
387 388 389 390 391 392
			if (empty_writes == 0) {
				msg_perr("Serial port is unresponsive!\n");
				return 1;
			}
		}
		writecnt -= tmp;
Patrick Georgi's avatar
Patrick Georgi committed
393
		buf += tmp;
394 395 396 397 398 399 400
	}

	return 0;
}

int serialport_read(unsigned char *buf, unsigned int readcnt)
{
401
#if IS_WINDOWS
402 403 404 405
	DWORD tmp = 0;
#else
	ssize_t tmp = 0;
#endif
406

Patrick Georgi's avatar
Patrick Georgi committed
407
	while (readcnt > 0) {
408
#if IS_WINDOWS
Patrick Georgi's avatar
Patrick Georgi committed
409 410
		ReadFile(sp_fd, buf, readcnt, &tmp, NULL);
#else
Patrick Georgi's avatar
Patrick Georgi committed
411
		tmp = read(sp_fd, buf, readcnt);
Patrick Georgi's avatar
Patrick Georgi committed
412
#endif
413 414
		if (tmp == -1) {
			msg_perr("Serial port read error!\n");
415
			return 1;
416
		}
417
		if (!tmp)
418
			msg_pdbg2("Empty read\n");
Patrick Georgi's avatar
Patrick Georgi committed
419 420
		readcnt -= tmp;
		buf += tmp;
421 422 423 424
	}

	return 0;
}
425 426 427 428 429 430 431 432

/* Tries up to timeout ms to read readcnt characters and places them into the array starting at c. Returns
 * 0 on success, positive values on temporary errors (e.g. timeouts) and negative ones on permanent errors.
 * If really_read is not NULL, this function sets its contents to the number of bytes read successfully. */
int serialport_read_nonblock(unsigned char *c, unsigned int readcnt, unsigned int timeout, unsigned int *really_read)
{
	int ret = 1;
	/* disable blocked i/o and declare platform-specific variables */
433
#if IS_WINDOWS
434 435 436 437 438 439 440 441 442 443 444 445 446 447
	DWORD rv;
	COMMTIMEOUTS oldTimeout;
	COMMTIMEOUTS newTimeout = {
		.ReadIntervalTimeout = MAXDWORD,
		.ReadTotalTimeoutMultiplier = 0,
		.ReadTotalTimeoutConstant = 0,
		.WriteTotalTimeoutMultiplier = 0,
		.WriteTotalTimeoutConstant = 0
	};
	if(!GetCommTimeouts(sp_fd, &oldTimeout)) {
		msg_perr_strerror("Could not get serial port timeout settings: ");
		return -1;
	}
	if(!SetCommTimeouts(sp_fd, &newTimeout)) {
448 449 450
		msg_perr_strerror("Could not set serial port timeout settings: ");
		return -1;
	}
451 452 453
#else
	ssize_t rv;
	const int flags = fcntl(sp_fd, F_GETFL);
454 455 456 457
	if (flags == -1) {
		msg_perr_strerror("Could not get serial port mode: ");
		return -1;
	}
458
	if (fcntl(sp_fd, F_SETFL, flags | O_NONBLOCK) != 0) {
459
		msg_perr_strerror("Could not set serial port mode to non-blocking: ");
460 461
		return -1;
	}
462
#endif
463 464 465 466 467

	int i;
	int rd_bytes = 0;
	for (i = 0; i < timeout; i++) {
		msg_pspew("readcnt %d rd_bytes %d\n", readcnt, rd_bytes);
468
#if IS_WINDOWS
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
		ReadFile(sp_fd, c + rd_bytes, readcnt - rd_bytes, &rv, NULL);
		msg_pspew("read %lu bytes\n", rv);
#else
		rv = read(sp_fd, c + rd_bytes, readcnt - rd_bytes);
		msg_pspew("read %zd bytes\n", rv);
#endif
		if ((rv == -1) && (errno != EAGAIN)) {
			msg_perr_strerror("Serial port read error: ");
			ret = -1;
			break;
		}
		if (rv > 0)
			rd_bytes += rv;
		if (rd_bytes == readcnt) {
			ret = 0;
			break;
		}
		internal_delay(1000);	/* 1ms units */
	}
	if (really_read != NULL)
		*really_read = rd_bytes;

	/* restore original blocking behavior */
492
#if IS_WINDOWS
493
	if (!SetCommTimeouts(sp_fd, &oldTimeout)) {
494 495 496
		msg_perr_strerror("Could not restore serial port timeout settings: ");
		ret = -1;
	}
497 498
#else
	if (fcntl(sp_fd, F_SETFL, flags) != 0) {
499
		msg_perr_strerror("Could not restore serial port mode to blocking: ");
500 501
		ret = -1;
	}
502
#endif
503 504
	return ret;
}
505 506 507 508

/* Tries up to timeout ms to write writecnt characters from the array starting at buf. Returns
 * 0 on success, positive values on temporary errors (e.g. timeouts) and negative ones on permanent errors.
 * If really_wrote is not NULL, this function sets its contents to the number of bytes written successfully. */
509
int serialport_write_nonblock(const unsigned char *buf, unsigned int writecnt, unsigned int timeout, unsigned int *really_wrote)
510 511 512
{
	int ret = 1;
	/* disable blocked i/o and declare platform-specific variables */
513
#if IS_WINDOWS
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
	DWORD rv;
	COMMTIMEOUTS oldTimeout;
	COMMTIMEOUTS newTimeout = {
		.ReadIntervalTimeout = MAXDWORD,
		.ReadTotalTimeoutMultiplier = 0,
		.ReadTotalTimeoutConstant = 0,
		.WriteTotalTimeoutMultiplier = 0,
		.WriteTotalTimeoutConstant = 0
	};
	if(!GetCommTimeouts(sp_fd, &oldTimeout)) {
		msg_perr_strerror("Could not get serial port timeout settings: ");
		return -1;
	}
	if(!SetCommTimeouts(sp_fd, &newTimeout)) {
		msg_perr_strerror("Could not set serial port timeout settings: ");
		return -1;
	}
#else
	ssize_t rv;
	const int flags = fcntl(sp_fd, F_GETFL);
534 535 536 537 538 539 540 541
	if (flags == -1) {
		msg_perr_strerror("Could not get serial port mode: ");
		return -1;
	}
	if (fcntl(sp_fd, F_SETFL, flags | O_NONBLOCK) != 0) {
		msg_perr_strerror("Could not set serial port mode to non-blocking: ");
		return -1;
	}
542 543 544 545 546 547
#endif

	int i;
	int wr_bytes = 0;
	for (i = 0; i < timeout; i++) {
		msg_pspew("writecnt %d wr_bytes %d\n", writecnt, wr_bytes);
548
#if IS_WINDOWS
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
		WriteFile(sp_fd, buf + wr_bytes, writecnt - wr_bytes, &rv, NULL);
		msg_pspew("wrote %lu bytes\n", rv);
#else
		rv = write(sp_fd, buf + wr_bytes, writecnt - wr_bytes);
		msg_pspew("wrote %zd bytes\n", rv);
#endif
		if ((rv == -1) && (errno != EAGAIN)) {
			msg_perr_strerror("Serial port write error: ");
			ret = -1;
			break;
		}
		if (rv > 0) {
			wr_bytes += rv;
			if (wr_bytes == writecnt) {
				msg_pspew("write successful\n");
				ret = 0;
				break;
			}
		}
		internal_delay(1000);	/* 1ms units */
	}
	if (really_wrote != NULL)
		*really_wrote = wr_bytes;

	/* restore original blocking behavior */
574
#if IS_WINDOWS
575 576
	if (!SetCommTimeouts(sp_fd, &oldTimeout)) {
		msg_perr_strerror("Could not restore serial port timeout settings: ");
577 578
		return -1;
	}
579 580
#else
	if (fcntl(sp_fd, F_SETFL, flags) != 0) {
581
		msg_perr_strerror("Could not restore serial port blocking behavior: ");
582 583
		return -1;
	}
584
#endif
585 586
	return ret;
}