[fuchsia] improve io performance

- reduce wait operations, try a read/write first
- increase buffer size to match io.fidl common message size
- avoid unnecessary non-blocking io

Change-Id: Ibc790edbe6bf445d1fbfa00203fafc58c65842a3
diff --git a/fuchsia/fuchsia-compat.c b/fuchsia/fuchsia-compat.c
index d6e56c1..151ae93 100644
--- a/fuchsia/fuchsia-compat.c
+++ b/fuchsia/fuchsia-compat.c
@@ -141,16 +141,18 @@
 	uint32_t events;
 	size_t offset = 0;
 	while (offset < length) {
-		if (fdio_wait_fd(fd, FDIO_EVT_WRITABLE|FDIO_EVT_PEER_CLOSED, &events, ZX_TIME_INFINITE) < 0) {
-			// Wait failed.
-			return false;
-		}
 		ssize_t length_written = write(fd, buffer + offset, length - offset);
 		if (length_written == -1 && errno == EAGAIN) {
-			// Wait and read again.
+			if (fdio_wait_fd(fd, FDIO_EVT_WRITABLE|FDIO_EVT_PEER_CLOSED, &events, ZX_TIME_INFINITE) < 0) {
+				// Wait failed.
+				return false;
+			}
+			if ((events & FDIO_EVT_PEER_CLOSED) != 0){
+				return false;
+			}
 			continue;
 		}
-		if (length_written <= 0) {
+		if (length_written == 0) {
 			// EOF or error.
 			return false;
 		}
@@ -165,15 +167,21 @@
 	pthread_detach(pthread_self());
 
 	int* fds = voidp;
-	char buf[128];
+	char buf[FDIO_CHUNK_SIZE];
 
 	for (;;) {
 		uint32_t events;
-		if (fdio_wait_fd(fds[0], FDIO_EVT_READABLE|FDIO_EVT_PEER_CLOSED, &events, ZX_TIME_INFINITE) < 0) {
-			// Wait failed.
-			break;
-		}
 		int length = read(fds[0], buf, sizeof(buf));
+		if (length == -1 && errno == EAGAIN) {
+			if (fdio_wait_fd(fds[0], FDIO_EVT_READABLE|FDIO_EVT_PEER_CLOSED, &events, ZX_TIME_INFINITE) < 0) {
+				// Wait failed.
+				break;
+			}
+			if ((events & FDIO_EVT_PEER_CLOSED) != 0) {
+				break;
+			}
+			continue;
+		}
 		if (length <= 0) {
 			// EOF or error.
 			break;
@@ -200,9 +208,6 @@
 		return -1;
 	}
 
-	set_nonblock(pip[0]);
-	set_nonblock(pip[1]);
-
 	// Allocate the structure to send the fds to the thread.
 	int* fds = malloc(2 * sizeof(int));
 	if (!fds) {
@@ -228,16 +233,22 @@
 	pthread_detach(pthread_self());
 
 	int* fds = voidp;
-	char buf[128];
+	char buf[FDIO_CHUNK_SIZE];
 
 	for (;;) {
-		uint32_t events;
-		if (fdio_wait_fd(fds[0], FDIO_EVT_READABLE|FDIO_EVT_PEER_CLOSED, &events, ZX_TIME_INFINITE) < 0) {
-			// Wait failed.
-			break;
-		}
 		int length = read(fds[0], buf, sizeof(buf));
-		if (length <= 0) {
+		if (length < 0) {
+			uint32_t events;
+			if (fdio_wait_fd(fds[0], FDIO_EVT_READABLE|FDIO_EVT_PEER_CLOSED, &events, ZX_TIME_INFINITE) < 0) {
+				// Wait failed.
+				break;
+			}
+			if ((events & FDIO_EVT_PEER_CLOSED) != 0) {
+				break;
+			}
+			continue;
+		}
+		if (length == 0) {
 			// EOF or error.
 			break;
 		}
@@ -289,9 +300,6 @@
 		return -1;
 	}
 
-	set_nonblock(pip[0]);
-	set_nonblock(pip[1]);
-
 	// Allocate the structure to send the fds to the thread.
 	int* fds = malloc(2 * sizeof(int));
 	if (!fds) {