comparison src/os/unix/ngx_recv.c @ 7583:efd71d49bde0

Events: available bytes calculation via ioctl(FIONREAD). This makes it possible to avoid looping for a long time while working with a fast enough peer when data are added to the socket buffer faster than we are able to read and process them (ticket #1431). This is basically what we already do on FreeBSD with kqueue, where information about the number of bytes in the socket buffer is returned by the kevent() call. With other event methods rev->available is now set to -1 when the socket is ready for reading. Later in ngx_recv() and ngx_recv_chain(), if full buffer is received, real number of bytes in the socket buffer is retrieved using ioctl(FIONREAD). Reading more than this number of bytes ensures that even with edge-triggered event methods the event will be triggered again, so it is safe to stop processing of the socket and switch to other connections. Using ioctl(FIONREAD) only after reading a full buffer is an optimization. With this approach we only call ioctl(FIONREAD) when there are at least two recv()/readv() calls.
author Maxim Dounin <mdounin@mdounin.ru>
date Thu, 17 Oct 2019 16:02:19 +0300
parents f7849bfb6d21
children 5119c8150478
comparison
equal deleted inserted replaced
7582:70749256af79 7583:efd71d49bde0
55 if (ngx_event_flags & NGX_USE_EPOLL_EVENT) { 55 if (ngx_event_flags & NGX_USE_EPOLL_EVENT) {
56 ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0, 56 ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,
57 "recv: eof:%d, avail:%d", 57 "recv: eof:%d, avail:%d",
58 rev->pending_eof, rev->available); 58 rev->pending_eof, rev->available);
59 59
60 if (!rev->available && !rev->pending_eof) { 60 if (rev->available == 0 && !rev->pending_eof) {
61 rev->ready = 0; 61 rev->ready = 0;
62 return NGX_AGAIN; 62 return NGX_AGAIN;
63 } 63 }
64 } 64 }
65 65
110 110
111 rev->available = 0; 111 rev->available = 0;
112 } 112 }
113 113
114 return n; 114 return n;
115 }
116
117 #endif
118
119 #if (NGX_HAVE_FIONREAD)
120
121 if (rev->available >= 0) {
122 rev->available -= n;
123
124 /*
125 * negative rev->available means some additional bytes
126 * were received between kernel notification and recv(),
127 * and therefore ev->ready can be safely reset even for
128 * edge-triggered event methods
129 */
130
131 if (rev->available < 0) {
132 rev->available = 0;
133 rev->ready = 0;
134 }
135
136 ngx_log_debug1(NGX_LOG_DEBUG_EVENT, c->log, 0,
137 "recv: avail:%d", rev->available);
138
139 } else if ((size_t) n == size) {
140
141 if (ngx_socket_nread(c->fd, &rev->available) == -1) {
142 n = ngx_connection_error(c, ngx_socket_errno,
143 ngx_socket_nread_n " failed");
144 break;
145 }
146
147 ngx_log_debug1(NGX_LOG_DEBUG_EVENT, c->log, 0,
148 "recv: avail:%d", rev->available);
115 } 149 }
116 150
117 #endif 151 #endif
118 152
119 #if (NGX_HAVE_EPOLLRDHUP) 153 #if (NGX_HAVE_EPOLLRDHUP)