Subject: Re: bug#32452: 26.1; gnutls_try_handshake maxes out cpu retrying when server is a bit busy

From: Noam Postavsky <[email-masked]>
Date: Fri, 17 Aug 2018 18:10:32 -0400

Eli Zaretskii <[email-masked]> writes:

> In which case it's fine, we just need to do something in the loop to
> yield the CPU, like some nanosleep, perhaps?  And maybe enlarge the
> sleep period as time goes on?
>
> debbugs is terribly slow in a browser as well, right now.  But
> hundreds of attempts sounds excessive to me.

The debbugs server seems back to normal speeds now, I'm getting ~200
hits with it just like other servers.  The patch below brings it down to
15~20.  nanosleep isn't portable though right?  Not sure what to put
instead, it seems existing wait functions in Emacs are all tied up with
threads and processes, so I don't know if it's safe to call them here.

--- i/src/gnutls.c
+++ w/src/gnutls.c
@@ -550,6 +550,8 @@ gnutls_try_handshake (struct Lisp_Process *proc)
   if (non_blocking)
     proc->gnutls_p = true;
 
+  enum { MAX_DELAY_NS = 100 * 1000 * 1000 }; // Max 100ms delay.
+  struct timespec delay = { 0, 1000 };
   do
     {
       ret = gnutls_handshake (state);
@@ -558,7 +560,9 @@ gnutls_try_handshake (struct Lisp_Process *proc)
     }
   while (ret < 0
 	 && gnutls_error_is_fatal (ret) == 0
-	 && ! non_blocking);
+	 && ! non_blocking
+         && (nanosleep (&delay, NULL),
+             delay.tv_nsec = min (delay.tv_nsec * 2, MAX_DELAY_NS)));
 
   proc->gnutls_initstage = GNUTLS_STAGE_HANDSHAKE_TRIED;