From 48fed5c55b5183e6d44702dfdccd3b5325d8689c Mon Sep 17 00:00:00 2001
From: David Herrmann <dh.herrmann@gmail.com>
Date: Fri, 3 Oct 2014 15:54:21 +0200
Subject: [PATCH] pty: optimize read loop

As it turns out, I can actually send data to the pty faster than the
terminal can read. Therefore, make sure we read as much data as possible
but bail out early enough to not cause starvation.

Kernel TTY buffers are 4k, so reduce the overall buffer size, but read
more than once if possible (up to 8 times sounds reasonable).
---
 src/shared/pty.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/src/shared/pty.c b/src/shared/pty.c
index adcb32d0be..52a426c0e1 100644
--- a/src/shared/pty.c
+++ b/src/shared/pty.c
@@ -67,7 +67,7 @@
 #include "ring.h"
 #include "util.h"
 
-#define PTY_BUFSIZE 16384
+#define PTY_BUFSIZE 4096
 
 enum {
         PTY_ROLE_UNKNOWN,
@@ -305,11 +305,11 @@ static int pty_dispatch_read(Pty *pty) {
         /*
          * We're edge-triggered, means we need to read the whole queue. This,
          * however, might cause us to stall if the writer is faster than we
-         * are. Therefore, we read twice and if the second read still returned
-         * data, we reschedule.
+         * are. Therefore, try reading as much as 8 times (32KiB) and only
+         * bail out then.
          */
 
-        for (i = 0; i < 2; ++i) {
+        for (i = 0; i < 8; ++i) {
                 len = read(pty->fd, pty->in_buf, sizeof(pty->in_buf) - 1);
                 if (len < 0) {
                         if (errno == EINTR)