- /* Start write. */
- if (WriteFile(port->hdl, buf, count, NULL, &port->write_ovl)) {
- DEBUG("Write completed immediately");
- RETURN_INT(count);
- } else if (GetLastError() == ERROR_IO_PENDING) {
- DEBUG("Waiting for write to complete");
- if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
- if (GetLastError() == ERROR_SEM_TIMEOUT) {
- DEBUG("Write timed out");
- RETURN_INT(0);
- } else {
- RETURN_FAIL("GetOverlappedResult() failed");
+ remaining_ms = timeout_remaining_ms(&timeout);
+
+ if (port->timeouts.WriteTotalTimeoutConstant != remaining_ms) {
+ port->timeouts.WriteTotalTimeoutConstant = remaining_ms;
+ if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
+ RETURN_FAIL("SetCommTimeouts() failed");
+ }
+
+ /* Reduce write size if it exceeds the WriteFile limit. */
+ write_size = count - total_bytes_written;
+ if (write_size > WRITEFILE_MAX_SIZE)
+ write_size = WRITEFILE_MAX_SIZE;
+
+ /* Start write. */
+
+ result = WriteFile(port->hdl, write_ptr, write_size, NULL, &port->write_ovl);
+
+ timeout_update(&timeout);
+
+ if (result) {
+ DEBUG("Write completed immediately");
+ bytes_written = write_size;
+ } else if (GetLastError() == ERROR_IO_PENDING) {
+ DEBUG("Waiting for write to complete");
+ if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
+ if (GetLastError() == ERROR_SEM_TIMEOUT) {
+ DEBUG("Write timed out");
+ break;
+ } else {
+ RETURN_FAIL("GetOverlappedResult() failed");
+ }