0f2f201b696f9a95f43a1353865ba8f5301a38cc
[crypto.git] / lib / silcutil / unix / silcunixschedule.c
1 /*
2
3   silcunixschedule.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1998 - 2007 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19 /* $Id$ */
20
21 #include "silc.h"
22
23 #if defined(HAVE_EPOLL_WAIT)
24 #include <sys/epoll.h>
25 #elif defined(HAVE_POLL) && defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
26 #include <poll.h>
27 #endif
28
29 const SilcScheduleOps schedule_ops;
30
31 /* Internal context. */
32 typedef struct {
33 #if defined(HAVE_EPOLL_WAIT)
34   struct epoll_event *fds;
35   SilcUInt32 fds_count;
36   int epfd;
37 #elif defined(HAVE_POLL) && defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
38   struct rlimit nofile;
39   struct pollfd *fds;
40   SilcUInt32 fds_count;
41 #endif /* HAVE_POLL && HAVE_SETRLIMIT && RLIMIT_NOFILE */
42   void *app_context;
43   int wakeup_pipe[2];
44   SilcTask wakeup_task;
45   sigset_t signals;
46   sigset_t signals_blocked;
47 } *SilcUnixScheduler;
48
49 typedef struct {
50   SilcUInt32 sig;
51   SilcTaskCallback callback;
52   void *context;
53   SilcBool call;
54   SilcSchedule schedule;
55 } SilcUnixSignal;
56
57 #define SIGNAL_COUNT 32
58 SilcUnixSignal signal_call[SIGNAL_COUNT];
59
60 #if defined(HAVE_EPOLL_WAIT)
61
62 /* Linux's fast epoll system (level triggered) */
63
64 int silc_epoll(SilcSchedule schedule, void *context)
65 {
66   SilcUnixScheduler internal = context;
67   SilcTaskFd task;
68   struct epoll_event *fds = internal->fds;
69   SilcUInt32 fds_count = internal->fds_count;
70   int ret, i, timeout = -1;
71
72   /* Allocate larger fd table if needed */
73   i = silc_hash_table_count(schedule->fd_queue);
74   if (i > fds_count) {
75     fds = silc_realloc(internal->fds, sizeof(*internal->fds) *
76                        (fds_count + (i / 2)));
77     if (silc_likely(fds)) {
78       internal->fds = fds;
79       internal->fds_count = fds_count = fds_count + (i / 2);
80     }
81   }
82
83   if (schedule->has_timeout)
84     timeout = ((schedule->timeout.tv_sec * 1000) +
85                (schedule->timeout.tv_usec / 1000));
86
87   SILC_SCHEDULE_UNLOCK(schedule);
88   ret = epoll_wait(internal->epfd, fds, fds_count, timeout);
89   SILC_SCHEDULE_LOCK(schedule);
90   if (ret <= 0)
91     return ret;
92
93   silc_list_init(schedule->fd_dispatch, struct SilcTaskStruct, next);
94
95   for (i = 0; i < ret; i++) {
96     task = fds[i].data.ptr;
97     task->revents = 0;
98     if (!task->header.valid || !task->events) {
99       epoll_ctl(internal->epfd, EPOLL_CTL_DEL, task->fd, &fds[i]);
100       continue;
101     }
102     if (fds[i].events & (EPOLLIN | EPOLLPRI | EPOLLHUP | EPOLLERR))
103       task->revents |= SILC_TASK_READ;
104     if (fds[i].events & EPOLLOUT)
105       task->revents |= SILC_TASK_WRITE;
106     silc_list_add(schedule->fd_dispatch, task);
107   }
108
109   return ret;
110 }
111
112 #elif defined(HAVE_POLL) && defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
113
114 /* Calls normal poll() system call. */
115
116 int silc_poll(SilcSchedule schedule, void *context)
117 {
118   SilcUnixScheduler internal = context;
119   SilcHashTableList htl;
120   SilcTaskFd task;
121   struct pollfd *fds = internal->fds;
122   SilcUInt32 fds_count = internal->fds_count;
123   int fd, ret, i = 0, timeout = -1;
124   void *fdp;
125
126   silc_hash_table_list(schedule->fd_queue, &htl);
127   while (silc_hash_table_get(&htl, &fdp, (void *)&task)) {
128     if (!task->events)
129       continue;
130     fd = SILC_PTR_TO_32(fdp);
131
132     /* Allocate larger fd table if needed */
133     if (i >= fds_count) {
134       struct rlimit nofile;
135
136       fds = silc_realloc(internal->fds, sizeof(*internal->fds) *
137                          (fds_count + (fds_count / 2)));
138       if (silc_unlikely(!fds))
139         break;
140       internal->fds = fds;
141       internal->fds_count = fds_count = fds_count + (fds_count / 2);
142       internal->nofile.rlim_cur = fds_count;
143       if (fds_count > internal->nofile.rlim_max)
144         internal->nofile.rlim_max = fds_count;
145       if (setrlimit(RLIMIT_NOFILE, &nofile) < 0)
146         break;
147     }
148
149     fds[i].fd = fd;
150     fds[i].events = 0;
151     task->revents = fds[i].revents = 0;
152
153     if (task->events & SILC_TASK_READ)
154       fds[i].events |= (POLLIN | POLLPRI);
155     if (task->events & SILC_TASK_WRITE)
156       fds[i].events |= POLLOUT;
157     i++;
158   }
159   silc_hash_table_list_reset(&htl);
160   silc_list_init(schedule->fd_dispatch, struct SilcTaskStruct, next);
161
162   if (schedule->has_timeout)
163     timeout = ((schedule->timeout.tv_sec * 1000) +
164                (schedule->timeout.tv_usec / 1000));
165
166   fds_count = i;
167   SILC_SCHEDULE_UNLOCK(schedule);
168   ret = poll(fds, fds_count, timeout);
169   SILC_SCHEDULE_LOCK(schedule);
170   if (ret <= 0)
171     return ret;
172
173   for (i = 0; i < fds_count; i++) {
174     if (!fds[i].revents)
175       continue;
176     if (!silc_hash_table_find(schedule->fd_queue, SILC_32_TO_PTR(fds[i].fd),
177                               NULL, (void *)&task))
178       continue;
179     if (!task->header.valid || !task->events)
180       continue;
181
182     fd = fds[i].revents;
183     if (fd & (POLLIN | POLLPRI | POLLERR | POLLHUP | POLLNVAL))
184       task->revents |= SILC_TASK_READ;
185     if (fd & POLLOUT)
186       task->revents |= SILC_TASK_WRITE;
187     silc_list_add(schedule->fd_dispatch, task);
188   }
189
190   return ret;
191 }
192
193 #else
194
195 /* Calls normal select() system call. */
196
197 int silc_select(SilcSchedule schedule, void *context)
198 {
199   SilcHashTableList htl;
200   SilcTaskFd task;
201   fd_set in, out;
202   int fd, max_fd = 0, ret;
203   void *fdp;
204
205   FD_ZERO(&in);
206   FD_ZERO(&out);
207
208   silc_hash_table_list(schedule->fd_queue, &htl);
209   while (silc_hash_table_get(&htl, &fdp, (void *)&task)) {
210     if (!task->events)
211       continue;
212     fd = SILC_PTR_TO_32(fdp);
213
214 #ifdef FD_SETSIZE
215     if (fd >= FD_SETSIZE)
216       break;
217 #endif /* FD_SETSIZE */
218
219     if (fd > max_fd)
220       max_fd = fd;
221
222     if (task->events & SILC_TASK_READ)
223       FD_SET(fd, &in);
224     if (task->events & SILC_TASK_WRITE)
225       FD_SET(fd, &out);
226
227     task->revents = 0;
228   }
229   silc_hash_table_list_reset(&htl);
230   silc_list_init(schedule->fd_dispatch, struct SilcTaskStruct, next);
231
232   SILC_SCHEDULE_UNLOCK(schedule);
233   ret = select(max_fd + 1, &in, &out, NULL, (schedule->has_timeout ?
234                                              &schedule->timeout : NULL));
235   SILC_SCHEDULE_LOCK(schedule);
236   if (ret <= 0)
237     return ret;
238
239   silc_hash_table_list(schedule->fd_queue, &htl);
240   while (silc_hash_table_get(&htl, &fdp, (void *)&task)) {
241     if (!task->header.valid || !task->events)
242       continue;
243     fd = SILC_PTR_TO_32(fdp);
244
245 #ifdef FD_SETSIZE
246     if (fd >= FD_SETSIZE)
247       break;
248 #endif /* FD_SETSIZE */
249
250     if (FD_ISSET(fd, &in))
251       task->revents |= SILC_TASK_READ;
252     if (FD_ISSET(fd, &out))
253       task->revents |= SILC_TASK_WRITE;
254     silc_list_add(schedule->fd_dispatch, task);
255   }
256   silc_hash_table_list_reset(&htl);
257
258   return ret;
259 }
260
261 #endif /* HAVE_POLL && HAVE_SETRLIMIT && RLIMIT_NOFILE */
262
263 /* Schedule `task' with events `event_mask'. Zero `event_mask' unschedules. */
264
265 SilcBool silc_schedule_internal_schedule_fd(SilcSchedule schedule,
266                                             void *context,
267                                             SilcTaskFd task,
268                                             SilcTaskEvent event_mask)
269 {
270 #if defined(HAVE_EPOLL_WAIT)
271   SilcUnixScheduler internal = (SilcUnixScheduler)context;
272   struct epoll_event event;
273
274   if (!internal)
275     return TRUE;
276
277   SILC_LOG_DEBUG(("Scheduling fd %lu, mask %x", task->fd, event_mask));
278
279   memset(&event, 0, sizeof(event));
280   if (event_mask & SILC_TASK_READ)
281     event.events |= (EPOLLIN | EPOLLPRI);
282   if (event_mask & SILC_TASK_WRITE)
283     event.events |= EPOLLOUT;
284
285   /* Zero mask unschedules task */
286   if (silc_unlikely(!event.events)) {
287     if (epoll_ctl(internal->epfd, EPOLL_CTL_DEL, task->fd, &event)) {
288       SILC_LOG_DEBUG(("epoll_ctl (DEL): %s", strerror(errno)));
289       return FALSE;
290     }
291     return TRUE;
292   }
293
294   /* Schedule the task */
295   if (silc_unlikely(!task->scheduled)) {
296     event.data.ptr = task;
297     if (epoll_ctl(internal->epfd, EPOLL_CTL_ADD, task->fd, &event)) {
298       SILC_LOG_DEBUG(("epoll_ctl (ADD): %s", strerror(errno)));
299       return FALSE;
300     }
301     task->scheduled = TRUE;
302     return TRUE;
303   }
304
305   /* Schedule for specific mask */
306   event.data.ptr = task;
307   if (epoll_ctl(internal->epfd, EPOLL_CTL_MOD, task->fd, &event)) {
308     SILC_LOG_DEBUG(("epoll_ctl (MOD): %s", strerror(errno)));
309     return FALSE;
310   }
311 #endif /* HAVE_EPOLL_WAIT */
312   return TRUE;
313 }
314
315 #ifdef SILC_THREADS
316
317 SILC_TASK_CALLBACK(silc_schedule_wakeup_cb)
318 {
319   SilcUnixScheduler internal = (SilcUnixScheduler)context;
320   unsigned char c;
321
322   SILC_LOG_DEBUG(("Wokeup"));
323
324   (void)read(internal->wakeup_pipe[0], &c, 1);
325 }
326
327 SILC_TASK_CALLBACK(silc_schedule_wakeup_init)
328 {
329   SilcUnixScheduler internal = schedule->internal;
330
331   internal->wakeup_task =
332     silc_schedule_task_add(schedule, internal->wakeup_pipe[0],
333                            silc_schedule_wakeup_cb, internal,
334                            0, 0, SILC_TASK_FD);
335   if (!internal->wakeup_task) {
336     SILC_LOG_WARNING(("Could not add a wakeup task, threads won't work"));
337     close(internal->wakeup_pipe[0]);
338     return;
339   }
340   silc_schedule_internal_schedule_fd(schedule, internal,
341                                      (SilcTaskFd)internal->wakeup_task,
342                                      SILC_TASK_READ);
343 }
344 #endif /* SILC_THREADS */
345
346 /* Initializes the platform specific scheduler.  This for example initializes
347    the wakeup mechanism of the scheduler.  In multi-threaded environment
348    the scheduler needs to be woken up when tasks are added or removed from
349    the task queues.  Returns context to the platform specific scheduler. */
350
351 void *silc_schedule_internal_init(SilcSchedule schedule,
352                                   void *app_context)
353 {
354   SilcUnixScheduler internal;
355   int i;
356
357   internal = silc_scalloc(schedule->stack, 1, sizeof(*internal));
358   if (!internal)
359     return NULL;
360
361 #if defined(HAVE_EPOLL_WAIT)
362   internal->epfd = epoll_create(4);
363   if (internal->epfd < 0) {
364     SILC_LOG_ERROR(("epoll_create() failed: %s", strerror(errno)));
365     return NULL;
366   }
367   internal->fds = silc_calloc(4, sizeof(*internal->fds));
368   if (!internal->fds) {
369     close(internal->epfd);
370     return NULL;
371   }
372   internal->fds_count = 4;
373 #elif defined(HAVE_POLL) && defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
374   getrlimit(RLIMIT_NOFILE, &internal->nofile);
375
376   if (schedule->max_tasks > 0) {
377     internal->nofile.rlim_cur = schedule->max_tasks;
378     if (schedule->max_tasks > internal->nofile.rlim_max)
379       internal->nofile.rlim_max = schedule->max_tasks;
380     setrlimit(RLIMIT_NOFILE, &internal->nofile);
381     getrlimit(RLIMIT_NOFILE, &internal->nofile);
382     schedule->max_tasks = internal->nofile.rlim_max;
383   }
384
385   internal->fds = silc_calloc(internal->nofile.rlim_cur,
386                               sizeof(*internal->fds));
387   if (!internal->fds)
388     return NULL;
389   internal->fds_count = internal->nofile.rlim_cur;
390 #endif /* HAVE_POLL && HAVE_SETRLIMIT && RLIMIT_NOFILE */
391
392   sigemptyset(&internal->signals);
393
394 #ifdef SILC_THREADS
395   if (pipe(internal->wakeup_pipe)) {
396     SILC_LOG_ERROR(("pipe() fails: %s", strerror(errno)));
397     return NULL;
398   }
399
400   silc_schedule_task_add_timeout(schedule, silc_schedule_wakeup_init,
401                                  internal, 0, 0);
402 #endif /* SILC_THREADS */
403
404   internal->app_context = app_context;
405
406   for (i = 0; i < SIGNAL_COUNT; i++) {
407     signal_call[i].sig = 0;
408     signal_call[i].call = FALSE;
409     signal_call[i].schedule = schedule;
410   }
411
412   return (void *)internal;
413 }
414
415 void silc_schedule_internal_signals_block(SilcSchedule schedule,
416                                           void *context);
417 void silc_schedule_internal_signals_unblock(SilcSchedule schedule,
418                                             void *context);
419
420 /* Uninitializes the platform specific scheduler context. */
421
422 void silc_schedule_internal_uninit(SilcSchedule schedule, void *context)
423 {
424   SilcUnixScheduler internal = (SilcUnixScheduler)context;
425
426   if (!internal)
427     return;
428
429 #ifdef SILC_THREADS
430   close(internal->wakeup_pipe[0]);
431   close(internal->wakeup_pipe[1]);
432 #endif
433
434 #if defined(HAVE_EPOLL_WAIT)
435   close(internal->epfd);
436   silc_free(internal->fds);
437 #elif defined(HAVE_POLL) && defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
438   silc_free(internal->fds);
439 #endif /* HAVE_POLL && HAVE_SETRLIMIT && RLIMIT_NOFILE */
440 }
441
442 /* Wakes up the scheduler */
443
444 void silc_schedule_internal_wakeup(SilcSchedule schedule, void *context)
445 {
446 #ifdef SILC_THREADS
447   SilcUnixScheduler internal = (SilcUnixScheduler)context;
448
449   if (!internal || !internal->wakeup_task)
450     return;
451
452   SILC_LOG_DEBUG(("Wakeup"));
453
454   (void)write(internal->wakeup_pipe[1], "!", 1);
455 #endif
456 }
457
458 /* Signal handler */
459
460 static void silc_schedule_internal_sighandler(int signal)
461 {
462   int i;
463
464   SILC_LOG_DEBUG(("Start"));
465
466   for (i = 0; i < SIGNAL_COUNT; i++) {
467     if (signal_call[i].sig == signal) {
468       signal_call[i].call = TRUE;
469       signal_call[i].schedule->signal_tasks = TRUE;
470       SILC_LOG_DEBUG(("Scheduling signal %d to be called",
471                       signal_call[i].sig));
472       break;
473     }
474   }
475 }
476
477 void silc_schedule_internal_signal_register(SilcSchedule schedule,
478                                             void *context,
479                                             SilcUInt32 sig,
480                                             SilcTaskCallback callback,
481                                             void *callback_context)
482 {
483   SilcUnixScheduler internal = (SilcUnixScheduler)context;
484   int i;
485
486   if (!internal)
487     return;
488
489   SILC_LOG_DEBUG(("Registering signal %d", sig));
490
491   silc_schedule_internal_signals_block(schedule, context);
492
493   for (i = 0; i < SIGNAL_COUNT; i++) {
494     if (!signal_call[i].sig) {
495       signal_call[i].sig = sig;
496       signal_call[i].callback = callback;
497       signal_call[i].context = callback_context;
498       signal_call[i].call = FALSE;
499       signal(sig, silc_schedule_internal_sighandler);
500       break;
501     }
502   }
503
504   silc_schedule_internal_signals_unblock(schedule, context);
505   sigaddset(&internal->signals, sig);
506 }
507
508 void silc_schedule_internal_signal_unregister(SilcSchedule schedule,
509                                               void *context,
510                                               SilcUInt32 sig)
511 {
512   SilcUnixScheduler internal = (SilcUnixScheduler)context;
513   int i;
514
515   if (!internal)
516     return;
517
518   SILC_LOG_DEBUG(("Unregistering signal %d", sig));
519
520   silc_schedule_internal_signals_block(schedule, context);
521
522   for (i = 0; i < SIGNAL_COUNT; i++) {
523     if (signal_call[i].sig == sig) {
524       signal_call[i].sig = 0;
525       signal_call[i].callback = NULL;
526       signal_call[i].context = NULL;
527       signal_call[i].call = FALSE;
528       signal(sig, SIG_DFL);
529     }
530   }
531
532   silc_schedule_internal_signals_unblock(schedule, context);
533   sigdelset(&internal->signals, sig);
534 }
535
536 /* Call all signals */
537
538 void silc_schedule_internal_signals_call(SilcSchedule schedule, void *context)
539 {
540   SilcUnixScheduler internal = (SilcUnixScheduler)context;
541   int i;
542
543   SILC_LOG_DEBUG(("Start"));
544
545   if (!internal)
546     return;
547
548   silc_schedule_internal_signals_block(schedule, context);
549
550   for (i = 0; i < SIGNAL_COUNT; i++) {
551     if (signal_call[i].call &&
552         signal_call[i].callback) {
553       SILC_LOG_DEBUG(("Calling signal %d callback",
554                       signal_call[i].sig));
555       silc_schedule_internal_signals_unblock(schedule, context);
556       signal_call[i].callback(schedule, internal->app_context,
557                               SILC_TASK_INTERRUPT,
558                               signal_call[i].sig,
559                               signal_call[i].context);
560       signal_call[i].call = FALSE;
561       silc_schedule_internal_signals_block(schedule, context);
562     }
563   }
564
565   silc_schedule_internal_signals_unblock(schedule, context);
566 }
567
568 /* Block registered signals in scheduler. */
569
570 void silc_schedule_internal_signals_block(SilcSchedule schedule, void *context)
571 {
572   SilcUnixScheduler internal = (SilcUnixScheduler)context;
573
574   if (!internal)
575     return;
576
577   sigprocmask(SIG_BLOCK, &internal->signals, &internal->signals_blocked);
578 }
579
580 /* Unblock registered signals in schedule. */
581
582 void silc_schedule_internal_signals_unblock(SilcSchedule schedule,
583                                             void *context)
584 {
585   SilcUnixScheduler internal = (SilcUnixScheduler)context;
586
587   if (!internal)
588     return;
589
590   sigprocmask(SIG_SETMASK, &internal->signals_blocked, NULL);
591 }
592
593 const SilcScheduleOps schedule_ops =
594 {
595   silc_schedule_internal_init,
596   silc_schedule_internal_uninit,
597 #if defined(HAVE_EPOLL_WAIT)
598   silc_epoll,
599 #elif defined(HAVE_POLL) && defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
600   silc_poll,
601 #else
602   silc_select,
603 #endif /* HAVE_POLL && HAVE_SETRLIMIT && RLIMIT_NOFILE */
604   silc_schedule_internal_schedule_fd,
605   silc_schedule_internal_wakeup,
606   silc_schedule_internal_signal_register,
607   silc_schedule_internal_signal_unregister,
608   silc_schedule_internal_signals_call,
609   silc_schedule_internal_signals_block,
610   silc_schedule_internal_signals_unblock,
611 };