e4fd20042120a216556f95cef53bb6b860170a4a
[ircu2.10.12-pk.git] / ircd / engine_devpoll.c
1 /*
2  * IRC - Internet Relay Chat, ircd/engine_devpoll.c
3  * Copyright (C) 2001 Kevin L. Mitchell <klmitch@mit.edu>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 1, or (at your option)
8  * any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 /** @file
20  * @brief Solaris /dev/poll event engine.
21  * @version $Id$
22  */
23 #include "config.h"
24
25 #include "ircd_events.h"
26
27 #include "ircd.h"
28 #include "ircd_alloc.h"
29 #include "ircd_features.h"
30 #include "ircd_log.h"
31 #include "s_debug.h"
32
33 /* #include <assert.h> -- Now using assert in ircd_log.h */
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <sys/devpoll.h>
37 #include <sys/poll.h>
38 #include <sys/socket.h>
39 #include <sys/stat.h>
40 #include <sys/types.h>
41 #include <unistd.h>
42
43 #define DEVPOLL_ERROR_THRESHOLD 20      /**< after 20 devpoll errors, restart */
44 #define ERROR_EXPIRE_TIME       3600    /**< expire errors after an hour */
45
46 /* Figure out what bits to set for read */
47 #if defined(POLLMSG) && defined(POLLIN) && defined(POLLRDNORM)
48 #  define POLLREADFLAGS (POLLMSG|POLLIN|POLLRDNORM)
49 #elif defined(POLLIN) && defined(POLLRDNORM)
50 #  define POLLREADFLAGS (POLLIN|POLLRDNORM)
51 #elif defined(POLLIN)
52 #  define POLLREADFLAGS POLLIN
53 #elif defined(POLLRDNORM)
54 #  define POLLREADFLAGS POLLRDNORM
55 #endif
56
57 /* Figure out what bits to set for write */
58 #if defined(POLLOUT) && defined(POLLWRNORM)
59 #  define POLLWRITEFLAGS (POLLOUT|POLLWRNORM)
60 #elif defined(POLLOUT)
61 #  define POLLWRITEFLAGS POLLOUT
62 #elif defined(POLLWRNORM)
63 #  define POLLWRITEFLAGS POLLWRNORM
64 #endif
65
66 /** Array of active Socket structures, indexed by file descriptor. */
67 static struct Socket** sockList;
68 /** Maximum file descriptor supported, plus one. */
69 static int devpoll_max;
70 /** File descriptor for /dev/poll device. */
71 static int devpoll_fd;
72
73 /** Number of recent errors from /dev/poll. */
74 static int errors = 0;
75 /** Periodic timer to forget errors. */
76 static struct Timer clear_error;
77 /** Array of currently polled file descriptors. */
78 static struct pollfd *polls;
79 /** Number of ::polls elements that have been populated. */
80 static int polls_used;
81 /** Current processing position in ::polls. */
82 static int polls_i;
83
84 /** Decrement the error count (once per hour).
85  * @param[in] ev Expired timer event (ignored).
86  */
87 static void
88 error_clear(struct Event* ev)
89 {
90   if (!--errors) /* remove timer when error count reaches 0 */
91     timer_del(ev_timer(ev));
92 }
93
94 /** Initialize the /dev/poll engine.
95  * @param[in] max_sockets Maximum number of file descriptors to support.
96  * @return Non-zero on success, or zero on failure.
97  */
98 static int
99 engine_init(int max_sockets)
100 {
101   int i;
102
103   if ((devpoll_fd = open("/dev/poll", O_RDWR)) < 0) {
104     log_write(LS_SYSTEM, L_WARNING, 0,
105               "/dev/poll engine cannot open device: %m");
106     return 0; /* engine cannot be initialized; defer */
107   }
108
109   /* allocate necessary memory */
110   sockList = (struct Socket**) MyMalloc(sizeof(struct Socket*) * max_sockets);
111
112   /* initialize the data */
113   for (i = 0; i < max_sockets; i++)
114     sockList[i] = 0;
115
116   devpoll_max = max_sockets; /* number of sockets allocated */
117
118   return 1;
119 }
120
121 /** Figure out what events go with a given state.
122  * @param[in] state %Socket state to consider.
123  * @param[in] events User-specified preferred event set.
124  * @return Actual set of preferred events.
125  */
126 static unsigned int
127 state_to_events(enum SocketState state, unsigned int events)
128 {
129   switch (state) {
130   case SS_CONNECTING: /* connecting socket */
131     return SOCK_EVENT_WRITABLE;
132     break;
133
134   case SS_LISTENING: /* listening socket */
135   case SS_NOTSOCK: /* our signal socket */
136     return SOCK_EVENT_READABLE;
137     break;
138
139   case SS_CONNECTED: case SS_DATAGRAM: case SS_CONNECTDG:
140     return events; /* ordinary socket */
141     break;
142   }
143
144   /*NOTREACHED*/
145   return 0;
146 }
147
148 /** Set the desired events for a socket.
149  * @param[in,out] sock Socket to operate on.
150  * @param[in] events User-specified preferred event set.
151  */
152 static void
153 set_events(struct Socket* sock, unsigned int events)
154 {
155   struct pollfd pfd;
156
157   pfd.fd = s_fd(sock);
158
159   if (s_ed_int(sock)) { /* is one in /dev/poll already? */
160     pfd.events = POLLREMOVE; /* First, remove old pollfd */
161
162     Debug((DEBUG_ENGINE, "devpoll: Removing old entry for socket %d [%p]",
163            s_fd(sock), sock));
164
165     if (write(devpoll_fd, &pfd, sizeof(pfd)) != sizeof(pfd)) {
166       event_generate(ET_ERROR, sock, errno); /* report error */
167       return;
168     }
169
170     s_ed_int(sock) = 0; /* mark that it's gone */
171   }
172
173   if (!(events & SOCK_EVENT_MASK)) /* no events, so stop here */
174     return;
175
176   pfd.events = 0; /* Now, set up new pollfd... */
177   if (events & SOCK_EVENT_READABLE)
178     pfd.events |= POLLREADFLAGS; /* look for readable conditions */
179   if (events & SOCK_EVENT_WRITABLE)
180     pfd.events |= POLLWRITEFLAGS; /* look for writable conditions */
181
182   Debug((DEBUG_ENGINE, "devpoll: Registering interest on %d [%p] (state %s, "
183          "mask [%s])", s_fd(sock), sock, state_to_name(s_state(sock)),
184          sock_flags(s_events(sock))));
185
186   if (write(devpoll_fd, &pfd, sizeof(pfd)) != sizeof(pfd)) {
187     event_generate(ET_ERROR, sock, errno); /* report error */
188     return;
189   }
190
191   s_ed_int(sock) = 1; /* mark that we've added a pollfd */
192 }
193
194 /** Add a socket to the event engine.
195  * @param[in] sock Socket to add to engine.
196  * @return Non-zero on success, or zero on error.
197  */
198 static int
199 engine_add(struct Socket* sock)
200 {
201   assert(0 != sock);
202   assert(0 == sockList[s_fd(sock)]);
203
204   /* bounds-check... */
205   if (s_fd(sock) >= devpoll_max) {
206     log_write(LS_SYSTEM, L_ERROR, 0,
207               "Attempt to add socket %d (> %d) to event engine", s_fd(sock),
208               devpoll_max);
209     return 0;
210   }
211
212   sockList[s_fd(sock)] = sock; /* add to list */
213
214   Debug((DEBUG_ENGINE, "devpoll: Adding socket %d [%p], state %s, to engine",
215          s_fd(sock), sock, state_to_name(s_state(sock))));
216
217   /* set the correct events */
218   set_events(sock, state_to_events(s_state(sock), s_events(sock)));
219
220   return 1; /* success */
221 }
222
223 /** Handle state transition for a socket.
224  * @param[in] sock Socket changing state.
225  * @param[in] new_state New state for socket.
226  */
227 static void
228 engine_state(struct Socket* sock, enum SocketState new_state)
229 {
230   assert(0 != sock);
231   assert(sock == sockList[s_fd(sock)]);
232
233   Debug((DEBUG_ENGINE, "devpoll: Changing state for socket %p to %s", sock,
234          state_to_name(new_state)));
235
236   /* set the correct events */
237   set_events(sock, state_to_events(new_state, s_events(sock)));
238 }
239
240 /** Handle change to preferred socket events.
241  * @param[in] sock Socket getting new interest list.
242  * @param[in] new_events New set of interesting events for socket.
243  */
244 static void
245 engine_events(struct Socket* sock, unsigned int new_events)
246 {
247   assert(0 != sock);
248   assert(sock == sockList[s_fd(sock)]);
249
250   Debug((DEBUG_ENGINE, "devpoll: Changing event mask for socket %p to [%s]",
251          sock, sock_flags(new_events)));
252
253   /* set the correct events */
254   set_events(sock, state_to_events(s_state(sock), new_events));
255 }
256
257 /** Remove a socket from the event engine.
258  * @param[in] sock Socket being destroyed.
259  */
260 static void
261 engine_delete(struct Socket* sock)
262 {
263   int ii;
264
265   assert(0 != sock);
266   assert(sock == sockList[s_fd(sock)]);
267
268   Debug((DEBUG_ENGINE, "devpoll: Deleting socket %d [%p], state %s",
269          s_fd(sock), sock, state_to_name(s_state(sock))));
270
271   set_events(sock, 0); /* get rid of the socket */
272
273   sockList[s_fd(sock)] = 0; /* zero the socket list entry */
274
275   /* Drop any unprocessed events citing this socket. */
276   for (ii = polls_i; ii < polls_used; ii++) {
277     if (polls[ii].fd == s_fd(sock)) {
278       polls[ii] = polls[--polls_used];
279     }
280   }
281 }
282
283 /** Run engine event loop.
284  * @param[in] gen Lists of generators of various types.
285  */
286 static void
287 engine_loop(struct Generators* gen)
288 {
289   struct dvpoll dopoll;
290   int polls_count;
291   struct Socket* sock;
292   struct pollfd *pfd;
293   int nfds;
294   int i;
295   int errcode;
296   socklen_t codesize;
297
298   if ((polls_count = feature_int(FEAT_POLLS_PER_LOOP)) < 20)
299     polls_count = 20;
300   polls = (struct pollfd *)MyMalloc(sizeof(struct pollfd) * polls_count);
301
302   while (running) {
303     if ((i = feature_int(FEAT_POLLS_PER_LOOP)) >= 20 && i != polls_count) {
304       polls = (struct pollfd *)MyRealloc(polls, sizeof(struct pollfd) * i);
305       polls_count = i;
306     }
307
308     dopoll.dp_fds = polls; /* set up the struct dvpoll */
309     dopoll.dp_nfds = polls_count;
310
311     /* calculate the proper timeout */
312     dopoll.dp_timeout = timer_next(gen) ?
313       (timer_next(gen) - CurrentTime) * 1000 : -1;
314
315     Debug((DEBUG_ENGINE, "devpoll: delay: %Tu (%Tu) %d", timer_next(gen),
316            CurrentTime, dopoll.dp_timeout));
317
318     /* check for active files */
319     polls_used = ioctl(devpoll_fd, DP_POLL, &dopoll);
320
321     CurrentTime = time(0); /* set current time... */
322
323     if (polls_used < 0) {
324       if (errno != EINTR) { /* ignore interrupts */
325         /* Log the poll error */
326         log_write(LS_SOCKET, L_ERROR, 0, "ioctl(DP_POLL) error: %m");
327         if (!errors++)
328           timer_add(timer_init(&clear_error), error_clear, 0, TT_PERIODIC,
329                     ERROR_EXPIRE_TIME);
330         else if (errors > DEVPOLL_ERROR_THRESHOLD) /* too many errors... */
331           server_restart("too many /dev/poll errors");
332       }
333       /* old code did a sleep(1) here; with usage these days,
334        * that may be too expensive
335        */
336       continue;
337     }
338
339     for (polls_i = 0; polls_i < polls_used; polls_i++) {
340       pfd = &polls[polls_i];
341       assert(-1 < pfd->fd);
342
343       sock = sockList[pfd->fd];
344       if (!sock) /* slots may become empty while processing events */
345         continue;
346
347       assert(s_fd(sock) == pfd->fd);
348
349       gen_ref_inc(sock); /* can't have it going away on us */
350
351       Debug((DEBUG_ENGINE, "devpoll: Checking socket %p (fd %d) state %s, "
352              "events %s", sock, s_fd(sock), state_to_name(s_state(sock)),
353              sock_flags(s_events(sock))));
354
355       if (s_state(sock) != SS_NOTSOCK) {
356         errcode = 0; /* check for errors on socket */
357         codesize = sizeof(errcode);
358         if (getsockopt(s_fd(sock), SOL_SOCKET, SO_ERROR, &errcode,
359                        &codesize) < 0)
360           errcode = errno; /* work around Solaris implementation */
361
362         if (errcode) { /* an error occurred; generate an event */
363           Debug((DEBUG_ENGINE, "devpoll: Error %d on fd %d, socket %p",
364                  errcode, s_fd(sock), sock));
365           event_generate(ET_ERROR, sock, errcode);
366           gen_ref_dec(sock); /* careful not to leak reference counts */
367           continue;
368         }
369       }
370
371       assert(!(pfd->revents & POLLERR));
372
373 #ifdef POLLHUP
374       if (pfd->revents & POLLHUP) { /* hang-up on socket */
375         Debug((DEBUG_ENGINE, "devpoll: EOF from client (POLLHUP)"));
376         event_generate(ET_EOF, sock, 0);
377         nfds--;
378         continue;
379       }
380 #endif /* POLLHUP */
381
382       switch (s_state(sock)) {
383       case SS_CONNECTING:
384         if (pfd->revents & POLLWRITEFLAGS) { /* connection completed */
385           Debug((DEBUG_ENGINE, "devpoll: Connection completed"));
386           event_generate(ET_CONNECT, sock, 0);
387         }
388         break;
389
390       case SS_LISTENING:
391         if (pfd->revents & POLLREADFLAGS) { /* connect. to be accept. */
392           Debug((DEBUG_ENGINE, "devpoll: Ready for accept"));
393           event_generate(ET_ACCEPT, sock, 0);
394         }
395         break;
396
397       case SS_NOTSOCK:
398         if (pfd->revents & POLLREADFLAGS) { /* data on socket */
399           /* can't peek; it's not a socket */
400           Debug((DEBUG_ENGINE, "devpoll: non-socket readable"));
401           event_generate(ET_READ, sock, 0);
402         }
403         break;
404
405       case SS_CONNECTED:
406         if (pfd->revents & POLLREADFLAGS) { /* data on socket */
407           char c;
408
409           switch (recv(s_fd(sock), &c, 1, MSG_PEEK)) { /* check EOF */
410           case -1: /* error occurred?!? */
411             if (errno == EAGAIN) {
412               Debug((DEBUG_ENGINE, "devpoll: Resource temporarily "
413                      "unavailable?"));
414               continue;
415             }
416             Debug((DEBUG_ENGINE, "devpoll: Uncaught error!"));
417             event_generate(ET_ERROR, sock, errno);
418             break;
419
420           case 0: /* EOF from client */
421             Debug((DEBUG_ENGINE, "devpoll: EOF from client"));
422             event_generate(ET_EOF, sock, 0);
423             break;
424
425           default: /* some data can be read */
426             Debug((DEBUG_ENGINE, "devpoll: Data to be read"));
427             event_generate(ET_READ, sock, 0);
428             break;
429           }
430         }
431         if (pfd->revents & POLLWRITEFLAGS) { /* socket writable */
432           Debug((DEBUG_ENGINE, "devpoll: Data can be written"));
433           event_generate(ET_WRITE, sock, 0);
434         }
435         break;
436
437       case SS_DATAGRAM: case SS_CONNECTDG:
438         if (pfd->revents & POLLREADFLAGS) { /* socket readable */
439           Debug((DEBUG_ENGINE, "devpoll: Datagram to be read"));
440           event_generate(ET_READ, sock, 0);
441         }
442         if (pfd->revents & POLLWRITEFLAGS) { /* socket writable */
443           Debug((DEBUG_ENGINE, "devpoll: Datagram can be written"));
444           event_generate(ET_WRITE, sock, 0);
445         }
446         break;
447       }
448
449       gen_ref_dec(sock); /* we're done with it */
450     }
451
452     timer_run(); /* execute any pending timers */
453   }
454 }
455
456 /** Descriptor for /dev/poll event engine. */
457 struct Engine engine_devpoll = {
458   "/dev/poll",          /* Engine name */
459   engine_init,          /* Engine initialization function */
460   0,                    /* Engine signal registration function */
461   engine_add,           /* Engine socket registration function */
462   engine_state,         /* Engine socket state change function */
463   engine_events,        /* Engine socket events mask function */
464   engine_delete,        /* Engine socket deletion function */
465   engine_loop           /* Core engine event loop */
466 };