2 * Copyright (C) 1996-2023 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 05 Socket Functions */
14 #include "anyp/PortCfg.h"
15 #include "comm/Connection.h"
16 #include "comm/Loops.h"
19 #include "mgr/Registration.h"
20 #include "StatCounters.h"
26 static int MAX_POLL_TIME
= 1000; /* see also Comm::QuickPollRequired() */
29 #define howmany(x, y) (((x)+((y)-1))/(y))
34 #define FD_MASK_BYTES sizeof(fd_mask)
35 #define FD_MASK_BITS (FD_MASK_BYTES*NBBY)
38 static int examine_select(fd_set
*, fd_set
*);
39 static int fdIsTcpListener(int fd
);
40 static int fdIsUdpListener(int fd
);
41 static int fdIsDns(int fd
);
42 static OBJH commIncomingStats
;
43 static int comm_check_incoming_select_handlers(int nfds
, int *fds
);
44 static void comm_select_dns_incoming(void);
45 static void commUpdateReadBits(int fd
, PF
* handler
);
46 static void commUpdateWriteBits(int fd
, PF
* handler
);
48 static struct timeval zero_tv
;
49 static fd_set global_readfds
;
50 static fd_set global_writefds
;
55 * Automatic tuning for incoming requests:
57 * INCOMING sockets are the ICP and HTTP ports. We need to check these
58 * fairly regularly, but how often? When the load increases, we
59 * want to check the incoming sockets more often. If we have a lot
60 * of incoming ICP, then we need to check these sockets more than
61 * if we just have HTTP.
63 * The variables 'incoming_udp_interval' and 'incoming_tcp_interval'
64 * determine how many normal I/O events to process before checking
65 * incoming sockets again. Note we store the incoming_interval
66 * multiplied by a factor of (2^INCOMING_FACTOR) to have some
67 * pseudo-floating point precision.
69 * The variable 'udp_io_events' and 'tcp_io_events' counts how many normal
70 * I/O events have been processed since the last check on the incoming
71 * sockets. When io_events > incoming_interval, its time to check incoming
74 * Every time we check incoming sockets, we count how many new messages
75 * or connections were processed. This is used to adjust the
76 * incoming_interval for the next iteration. The new incoming_interval
77 * is calculated as the current incoming_interval plus what we would
78 * like to see as an average number of events minus the number of
79 * events just processed.
81 * incoming_interval = incoming_interval + target_average - number_of_events_processed
83 * There are separate incoming_interval counters for DNS, UDP and TCP events
85 * You can see the current values of the incoming_interval's, as well as
86 * a histogram of 'incoming_events' by asking the cache manager
87 * for 'comm_incoming', e.g.:
89 * % ./client mgr:comm_incoming
93 * - We have MAX_INCOMING_INTEGER as a magic upper limit on
94 * incoming_interval for both types of sockets. At the
95 * largest value the cache will effectively be idling.
97 * - The higher the INCOMING_FACTOR, the slower the algorithm will
98 * respond to load spikes/increases/decreases in demand. A value
99 * between 3 and 8 is recommended.
102 #define MAX_INCOMING_INTEGER 256
103 #define INCOMING_FACTOR 5
104 #define MAX_INCOMING_INTERVAL (MAX_INCOMING_INTEGER << INCOMING_FACTOR)
105 static int udp_io_events
= 0;
106 static int dns_io_events
= 0;
107 static int tcp_io_events
= 0;
108 static int incoming_udp_interval
= 16 << INCOMING_FACTOR
;
109 static int incoming_dns_interval
= 16 << INCOMING_FACTOR
;
110 static int incoming_tcp_interval
= 16 << INCOMING_FACTOR
;
111 #define commCheckUdpIncoming (++udp_io_events > (incoming_udp_interval>> INCOMING_FACTOR))
112 #define commCheckDnsIncoming (++dns_io_events > (incoming_dns_interval>> INCOMING_FACTOR))
113 #define commCheckTcpIncoming (++tcp_io_events > (incoming_tcp_interval>> INCOMING_FACTOR))
116 Comm::SetSelect(int fd
, unsigned int type
, PF
* handler
, void *client_data
, time_t timeout
)
118 fde
*F
= &fd_table
[fd
];
120 assert(F
->flags
.open
|| (!handler
&& !client_data
&& !timeout
));
121 debugs(5, 5, "FD " << fd
<< ", type=" << type
<<
122 ", handler=" << handler
<< ", client_data=" << client_data
<<
123 ", timeout=" << timeout
);
125 if (type
& COMM_SELECT_READ
) {
126 F
->read_handler
= handler
;
127 F
->read_data
= client_data
;
128 commUpdateReadBits(fd
, handler
);
131 if (type
& COMM_SELECT_WRITE
) {
132 F
->write_handler
= handler
;
133 F
->write_data
= client_data
;
134 commUpdateWriteBits(fd
, handler
);
138 F
->timeout
= squid_curtime
+ timeout
;
142 fdIsUdpListener(int fd
)
144 if (icpIncomingConn
!= NULL
&& fd
== icpIncomingConn
->fd
)
147 if (icpOutgoingConn
!= NULL
&& fd
== icpOutgoingConn
->fd
)
156 if (fd
== DnsSocketA
)
159 if (fd
== DnsSocketB
)
166 fdIsTcpListener(int fd
)
168 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
169 if (s
->listenConn
!= NULL
&& s
->listenConn
->fd
== fd
)
177 comm_check_incoming_select_handlers(int nfds
, int *fds
)
186 FD_ZERO(&write_mask
);
187 incoming_sockets_accepted
= 0;
189 for (i
= 0; i
< nfds
; ++i
) {
192 if (fd_table
[fd
].read_handler
) {
193 FD_SET(fd
, &read_mask
);
199 if (fd_table
[fd
].write_handler
) {
200 FD_SET(fd
, &write_mask
);
212 ++ statCounter
.syscalls
.selects
;
214 if (select(maxfd
, &read_mask
, &write_mask
, nullptr, &zero_tv
) < 1)
215 return incoming_sockets_accepted
;
217 for (i
= 0; i
< nfds
; ++i
) {
220 if (FD_ISSET(fd
, &read_mask
)) {
221 if ((hdl
= fd_table
[fd
].read_handler
) != NULL
) {
222 fd_table
[fd
].read_handler
= nullptr;
223 commUpdateReadBits(fd
, nullptr);
224 hdl(fd
, fd_table
[fd
].read_data
);
226 debugs(5, DBG_IMPORTANT
, "comm_select_incoming: FD " << fd
<< " NULL read handler");
230 if (FD_ISSET(fd
, &write_mask
)) {
231 if ((hdl
= fd_table
[fd
].write_handler
) != NULL
) {
232 fd_table
[fd
].write_handler
= nullptr;
233 commUpdateWriteBits(fd
, nullptr);
234 hdl(fd
, fd_table
[fd
].write_data
);
236 debugs(5, DBG_IMPORTANT
, "comm_select_incoming: FD " << fd
<< " NULL write handler");
241 return incoming_sockets_accepted
;
245 comm_select_udp_incoming(void)
252 if (Comm::IsConnOpen(icpIncomingConn
)) {
253 fds
[nfds
] = icpIncomingConn
->fd
;
257 if (Comm::IsConnOpen(icpOutgoingConn
) && icpIncomingConn
!= icpOutgoingConn
) {
258 fds
[nfds
] = icpOutgoingConn
->fd
;
265 nevents
= comm_check_incoming_select_handlers(nfds
, fds
);
267 incoming_udp_interval
+= Config
.comm_incoming
.udp
.average
- nevents
;
269 if (incoming_udp_interval
< 0)
270 incoming_udp_interval
= 0;
272 if (incoming_udp_interval
> MAX_INCOMING_INTERVAL
)
273 incoming_udp_interval
= MAX_INCOMING_INTERVAL
;
275 if (nevents
> INCOMING_UDP_MAX
)
276 nevents
= INCOMING_UDP_MAX
;
278 statCounter
.comm_udp_incoming
.count(nevents
);
282 comm_select_tcp_incoming(void)
285 int fds
[MAXTCPLISTENPORTS
];
289 // XXX: only poll sockets that won't be deferred. But how do we identify them?
291 for (AnyP::PortCfgPointer s
= HttpPortList
; s
!= NULL
; s
= s
->next
) {
292 if (Comm::IsConnOpen(s
->listenConn
)) {
293 fds
[nfds
] = s
->listenConn
->fd
;
298 nevents
= comm_check_incoming_select_handlers(nfds
, fds
);
299 incoming_tcp_interval
+= Config
.comm_incoming
.tcp
.average
- nevents
;
301 if (incoming_tcp_interval
< 0)
302 incoming_tcp_interval
= 0;
304 if (incoming_tcp_interval
> MAX_INCOMING_INTERVAL
)
305 incoming_tcp_interval
= MAX_INCOMING_INTERVAL
;
307 if (nevents
> INCOMING_TCP_MAX
)
308 nevents
= INCOMING_TCP_MAX
;
310 statCounter
.comm_tcp_incoming
.count(nevents
);
313 /* Select on all sockets; call handlers for those that are ready. */
315 Comm::DoSelect(int msec
)
326 int calldns
= 0, calludp
= 0, calltcp
= 0;
328 struct timeval poll_time
;
329 double timeout
= current_dtime
+ (msec
/ 1000.0);
339 start
= current_dtime
;
341 if (commCheckUdpIncoming
)
342 comm_select_udp_incoming();
344 if (commCheckDnsIncoming
)
345 comm_select_dns_incoming();
347 if (commCheckTcpIncoming
)
348 comm_select_tcp_incoming();
350 calldns
= calludp
= calltcp
= 0;
352 maxfd
= Biggest_FD
+ 1;
354 memcpy(&readfds
, &global_readfds
, sizeof(global_readfds
));
356 memcpy(&writefds
, &global_writefds
, sizeof(global_writefds
));
358 memcpy(&errfds
, &global_writefds
, sizeof(global_writefds
));
360 /* remove stalled FDs, and deal with pending descriptors */
363 FD_ZERO(&pendingfds
);
365 for (j
= 0; j
< (int) readfds
.fd_count
; ++j
) {
366 register int readfds_handle
= readfds
.fd_array
[j
];
369 for ( fd
= Biggest_FD
; fd
; --fd
) {
370 if ( fd_table
[fd
].win32
.handle
== readfds_handle
) {
371 if (fd_table
[fd
].flags
.open
) {
381 if (FD_ISSET(fd
, &readfds
) && fd_table
[fd
].flags
.read_pending
) {
382 FD_SET(fd
, &pendingfds
);
387 if (nreadfds
+ nwritefds
== 0) {
388 assert(shutting_down
);
389 return Comm::SHUTDOWN
;
392 if (msec
> MAX_POLL_TIME
)
393 msec
= MAX_POLL_TIME
;
399 poll_time
.tv_sec
= msec
/ 1000;
400 poll_time
.tv_usec
= (msec
% 1000) * 1000;
401 ++ statCounter
.syscalls
.selects
;
402 num
= select(maxfd
, &readfds
, &writefds
, &errfds
, &poll_time
);
404 ++ statCounter
.select_loops
;
406 if (num
>= 0 || pending
> 0)
409 if (ignoreErrno(xerrno
))
412 debugs(5, DBG_CRITICAL
, MYNAME
<< "WARNING: select failure: " << xstrerr(xerrno
));
414 examine_select(&readfds
, &writefds
);
416 return Comm::COMM_ERROR
;
421 if (num
< 0 && !pending
)
426 debugs(5, num
? 5 : 8, "comm_select: " << num
<< "+" << pending
<< " FDs ready");
428 statCounter
.select_fds_hist
.count(num
);
430 if (num
== 0 && pending
== 0)
433 /* Scan return fd masks for ready descriptors */
434 assert(readfds
.fd_count
<= (unsigned int) Biggest_FD
);
435 assert(pendingfds
.fd_count
<= (unsigned int) Biggest_FD
);
437 for (j
= 0; j
< (int) readfds
.fd_count
; ++j
) {
438 register int readfds_handle
= readfds
.fd_array
[j
];
439 register int pendingfds_handle
= pendingfds
.fd_array
[j
];
440 register int osfhandle
;
443 for ( fd
= Biggest_FD
; fd
; --fd
) {
444 osfhandle
= fd_table
[fd
].win32
.handle
;
446 if (( osfhandle
== readfds_handle
) ||
447 ( osfhandle
== pendingfds_handle
)) {
448 if (fd_table
[fd
].flags
.open
) {
458 if (fdIsUdpListener(fd
)) {
468 if (fdIsTcpListener(fd
)) {
474 debugs(5, 6, "comm_select: FD " << fd
<< " ready for reading");
476 if ((hdl
= F
->read_handler
)) {
477 F
->read_handler
= nullptr;
478 commUpdateReadBits(fd
, nullptr);
479 hdl(fd
, F
->read_data
);
480 ++ statCounter
.select_fds
;
482 if (commCheckUdpIncoming
)
483 comm_select_udp_incoming();
485 if (commCheckDnsIncoming
)
486 comm_select_dns_incoming();
488 if (commCheckTcpIncoming
)
489 comm_select_tcp_incoming();
493 assert(errfds
.fd_count
<= (unsigned int) Biggest_FD
);
495 for (j
= 0; j
< (int) errfds
.fd_count
; ++j
) {
496 register int errfds_handle
= errfds
.fd_array
[j
];
498 for ( fd
= Biggest_FD
; fd
; --fd
) {
499 if ( fd_table
[fd
].win32
.handle
== errfds_handle
)
503 if (fd_table
[fd
].flags
.open
) {
506 if ((hdl
= F
->write_handler
)) {
507 F
->write_handler
= nullptr;
508 commUpdateWriteBits(fd
, nullptr);
509 hdl(fd
, F
->write_data
);
510 ++ statCounter
.select_fds
;
515 assert(writefds
.fd_count
<= (unsigned int) Biggest_FD
);
517 for (j
= 0; j
< (int) writefds
.fd_count
; ++j
) {
518 register int writefds_handle
= writefds
.fd_array
[j
];
521 for ( fd
= Biggest_FD
; fd
; --fd
) {
522 if ( fd_table
[fd
].win32
.handle
== writefds_handle
) {
523 if (fd_table
[fd
].flags
.open
) {
533 if (fdIsUdpListener(fd
)) {
543 if (fdIsTcpListener(fd
)) {
549 debugs(5, 6, "comm_select: FD " << fd
<< " ready for writing");
551 if ((hdl
= F
->write_handler
)) {
552 F
->write_handler
= nullptr;
553 commUpdateWriteBits(fd
, nullptr);
554 hdl(fd
, F
->write_data
);
555 ++ statCounter
.select_fds
;
557 if (commCheckUdpIncoming
)
558 comm_select_udp_incoming();
560 if (commCheckDnsIncoming
)
561 comm_select_dns_incoming();
563 if (commCheckTcpIncoming
)
564 comm_select_tcp_incoming();
569 comm_select_udp_incoming();
572 comm_select_dns_incoming();
575 comm_select_tcp_incoming();
579 statCounter
.select_time
+= (current_dtime
- start
);
582 } while (timeout
> current_dtime
);
583 debugs(5, 8, "comm_select: time out: " << squid_curtime
);
585 return Comm::TIMEOUT
;
589 comm_select_dns_incoming(void)
596 if (DnsSocketA
< 0 && DnsSocketB
< 0)
599 if (DnsSocketA
>= 0) {
600 fds
[nfds
] = DnsSocketA
;
604 if (DnsSocketB
>= 0) {
605 fds
[nfds
] = DnsSocketB
;
609 nevents
= comm_check_incoming_select_handlers(nfds
, fds
);
614 incoming_dns_interval
+= Config
.comm_incoming
.dns
.average
- nevents
;
616 if (incoming_dns_interval
< Config
.comm_incoming
.dns
.min_poll
)
617 incoming_dns_interval
= Config
.comm_incoming
.dns
.min_poll
;
619 if (incoming_dns_interval
> MAX_INCOMING_INTERVAL
)
620 incoming_dns_interval
= MAX_INCOMING_INTERVAL
;
622 if (nevents
> INCOMING_DNS_MAX
)
623 nevents
= INCOMING_DNS_MAX
;
625 statCounter
.comm_dns_incoming
.count(nevents
);
629 Comm::SelectLoopInit(void)
633 FD_ZERO(&global_readfds
);
634 FD_ZERO(&global_writefds
);
635 nreadfds
= nwritefds
= 0;
637 Mgr::RegisterAction("comm_select_incoming",
638 "comm_incoming() stats",
639 commIncomingStats
, 0, 1);
643 * examine_select - debug routine.
645 * I spend the day chasing this core dump that occurs when both the client
646 * and the server side of a cache fetch simultaneoulsy abort the
647 * connection. While I haven't really studied the code to figure out how
648 * it happens, the snippet below may prevent the cache from exitting:
650 * Call this from where the select loop fails.
653 examine_select(fd_set
* readfds
, fd_set
* writefds
)
660 AsyncCall::Pointer ch
= nullptr;
664 debugs(5, DBG_CRITICAL
, "examine_select: Examining open file descriptors...");
666 for (fd
= 0; fd
< Squid_MaxFD
; ++fd
) {
669 tv
.tv_sec
= tv
.tv_usec
= 0;
671 if (FD_ISSET(fd
, readfds
))
673 else if (FD_ISSET(fd
, writefds
))
674 FD_SET(fd
, &write_x
);
678 ++ statCounter
.syscalls
.selects
;
681 if (!fstat(fd
, &sb
)) {
682 debugs(5, 5, "FD " << fd
<< " is valid.");
688 debugs(5, DBG_CRITICAL
, "fstat(FD " << fd
<< "): " << xstrerr(xerrno
));
689 debugs(5, DBG_CRITICAL
, "WARNING: FD " << fd
<< " has handlers, but it's invalid.");
690 debugs(5, DBG_CRITICAL
, "FD " << fd
<< " is a " << fdTypeStr
[F
->type
] << " called '" << F
->desc
<< "'");
691 debugs(5, DBG_CRITICAL
, "tmout:" << F
->timeoutHandler
<< " read:" << F
->read_handler
<< " write:" << F
->write_handler
);
693 for (ch
= F
->closeHandler
; ch
!= NULL
; ch
= ch
->Next())
694 debugs(5, DBG_CRITICAL
, " close handler: " << ch
);
696 if (F
->closeHandler
!= NULL
) {
697 commCallCloseHandlers(fd
);
698 } else if (F
->timeoutHandler
!= NULL
) {
699 debugs(5, DBG_CRITICAL
, "examine_select: Calling Timeout Handler");
700 ScheduleCallHere(F
->timeoutHandler
);
703 F
->closeHandler
= nullptr;
704 F
->timeoutHandler
= nullptr;
705 F
->read_handler
= nullptr;
706 F
->write_handler
= nullptr;
708 FD_CLR(fd
, writefds
);
715 commIncomingStats(StoreEntry
* sentry
)
717 storeAppendPrintf(sentry
, "Current incoming_udp_interval: %d\n",
718 incoming_udp_interval
>> INCOMING_FACTOR
);
719 storeAppendPrintf(sentry
, "Current incoming_dns_interval: %d\n",
720 incoming_dns_interval
>> INCOMING_FACTOR
);
721 storeAppendPrintf(sentry
, "Current incoming_tcp_interval: %d\n",
722 incoming_tcp_interval
>> INCOMING_FACTOR
);
723 storeAppendPrintf(sentry
, "\n");
724 storeAppendPrintf(sentry
, "Histogram of events per incoming socket type\n");
725 storeAppendPrintf(sentry
, "ICP Messages handled per comm_select_udp_incoming() call:\n");
726 statCounter
.comm_udp_incoming
.dump(sentry
, statHistIntDumper
);
727 storeAppendPrintf(sentry
, "DNS Messages handled per comm_select_dns_incoming() call:\n");
728 statCounter
.comm_dns_incoming
.dump(sentry
, statHistIntDumper
);
729 storeAppendPrintf(sentry
, "HTTP Messages handled per comm_select_tcp_incoming() call:\n");
730 statCounter
.comm_tcp_incoming
.dump(sentry
, statHistIntDumper
);
734 commUpdateReadBits(int fd
, PF
* handler
)
736 if (handler
&& !FD_ISSET(fd
, &global_readfds
)) {
737 FD_SET(fd
, &global_readfds
);
739 } else if (!handler
&& FD_ISSET(fd
, &global_readfds
)) {
740 FD_CLR(fd
, &global_readfds
);
746 commUpdateWriteBits(int fd
, PF
* handler
)
748 if (handler
&& !FD_ISSET(fd
, &global_writefds
)) {
749 FD_SET(fd
, &global_writefds
);
751 } else if (!handler
&& FD_ISSET(fd
, &global_writefds
)) {
752 FD_CLR(fd
, &global_writefds
);
757 /* Called by async-io or diskd to speed up the polling */
759 Comm::QuickPollRequired(void)
764 #endif /* USE_SELECT_WIN32 */