Merged silc_1_0_branch to trunk.
[silc.git] / lib / silcutil / silcschedule.c
1 /*
2
3   silcschedule.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1998 - 2003 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 "silcincludes.h"
22 #include "silcschedule_i.h"
23
24 /* Forward declarations */
25 typedef struct SilcTaskQueueStruct *SilcTaskQueue;
26
27 /* System specific routines. Implemented under unix/, win32/ and such. */
28
29 /* System specific select(). Returns same values as normal select(). */
30 int silc_select(SilcScheduleFd fds, SilcUInt32 fds_count,
31                 struct timeval *timeout);
32
33 /* Initializes the platform specific scheduler.  This for example initializes
34    the wakeup mechanism of the scheduler.  In multi-threaded environment
35    the scheduler needs to be wakenup when tasks are added or removed from
36    the task queues.  Returns context to the platform specific scheduler. */
37 void *silc_schedule_internal_init(SilcSchedule schedule, void *context);
38
39 /* Uninitializes the platform specific scheduler context. */
40 void silc_schedule_internal_uninit(void *context);
41
42 /* Wakes up the scheduler. This is platform specific routine */
43 void silc_schedule_internal_wakeup(void *context);
44
45 /* Register signal */
46 void silc_schedule_internal_signal_register(void *context,
47                                             SilcUInt32 signal,
48                                             SilcTaskCallback callback,
49                                             void *callback_context);
50
51 /* Unregister signal */
52 void silc_schedule_internal_signal_unregister(void *context,
53                                               SilcUInt32 signal,
54                                               SilcTaskCallback callback,
55                                               void *callback_context);
56
57 /* Mark signal to be called later. */
58 void silc_schedule_internal_signal_call(void *context, SilcUInt32 signal);
59
60 /* Call all signals */
61 void silc_schedule_internal_signals_call(void *context,
62                                          SilcSchedule schedule);
63
64 /* Block registered signals in scheduler. */
65 void silc_schedule_internal_signals_block(void *context);
66
67 /* Unblock registered signals in schedule. */
68 void silc_schedule_internal_signals_unblock(void *context);
69
70 /* Internal task management routines. */
71
72 static void silc_schedule_dispatch_timeout(SilcSchedule schedule,
73                                            bool dispatch_all);
74 static void silc_task_queue_alloc(SilcTaskQueue *queue);
75 static void silc_task_queue_free(SilcTaskQueue queue);
76 static SilcTask silc_task_find(SilcTaskQueue queue, SilcUInt32 fd);
77 static SilcTask silc_task_add(SilcTaskQueue queue, SilcTask newtask,
78                               SilcTaskPriority priority);
79 static SilcTask silc_task_get_first(SilcTaskQueue queue, SilcTask first);
80 static SilcTask silc_task_add_timeout(SilcTaskQueue queue, SilcTask newtask,
81                                       SilcTaskPriority priority);
82 static int silc_schedule_task_remove(SilcTaskQueue queue, SilcTask task);
83 static void silc_task_del_by_context(SilcTaskQueue queue, void *context);
84 static void silc_task_del_by_callback(SilcTaskQueue queue,
85                                       SilcTaskCallback callback);
86 static void silc_task_del_by_fd(SilcTaskQueue queue, SilcUInt32 fd);
87
88 /* Returns the task queue by task type */
89 #define SILC_SCHEDULE_GET_QUEUE(type)                           \
90   (type == SILC_TASK_FD ? schedule->fd_queue :                  \
91    type == SILC_TASK_TIMEOUT ? schedule->timeout_queue :        \
92    schedule->generic_queue)
93
94 /* Locks. These also blocks signals that we care about and thus guarantee
95    that while we are in scheduler no signals can happen.  This way we can
96    synchronise signals with SILC Scheduler. */
97 #define SILC_SCHEDULE_LOCK(schedule)                            \
98 do {                                                            \
99   silc_schedule_internal_signals_block(schedule->internal);     \
100   silc_mutex_lock(schedule->lock);                              \
101 } while (0)
102 #define SILC_SCHEDULE_UNLOCK(schedule)                          \
103 do {                                                            \
104   silc_mutex_unlock(schedule->lock);                            \
105   silc_schedule_internal_signals_unblock(schedule->internal);   \
106 } while (0)
107
108 /* SILC Task object. Represents one task in the scheduler. */
109 struct SilcTaskStruct {
110   SilcUInt32 fd;
111   SilcTaskCallback callback;       /* Task callback */
112   void *context;                   /* Task callback context */
113   struct timeval timeout;          /* Set for timeout tasks */
114   unsigned int valid : 1;          /* Set when task is valid */
115   unsigned int priority : 2;       /* Priority of the task */
116   unsigned int type : 5;           /* Type of the task */
117
118   /* Pointers forming doubly linked circular list */
119   struct SilcTaskStruct *next;
120   struct SilcTaskStruct *prev;
121 };
122
123 /* SILC Task Queue object. The queue holds all the tasks in the scheduler.
124    There are always three task queues in the scheduler. One for non-timeout
125    tasks (fd tasks performing tasks over specified file descriptor),
126    one for timeout tasks and one for generic tasks. */
127 struct SilcTaskQueueStruct {
128   SilcTask task;                /* Pointer to all tasks */
129   struct timeval timeout;       /* Current timeout */
130   SILC_MUTEX_DEFINE(lock);      /* Queue's lock */
131 };
132
133 /*
134    SILC Scheduler structure.
135
136    This is the actual schedule object in SILC. Both SILC client and server
137    uses this same scheduler. Actually, this scheduler could be used by any
138    program needing scheduling.
139
140    Following short description of the fields:
141
142    SilcTaskQueue fd_queue
143
144        Task queue hook for non-timeout tasks. Usually this means that these
145        tasks perform different kind of I/O on file descriptors. File
146        descriptors are usually network sockets but they actually can be
147        any file descriptors. This hook is initialized in silc_schedule_init
148        function. Timeout tasks should not be added to this queue because
149        they will never expire.
150
151    SilcTaskQueue timeout_queue
152
153        Task queue hook for timeout tasks. This hook is reserved specificly
154        for tasks with timeout. Non-timeout tasks should not be added to this
155        queue because they will never get scheduled. This hook is also
156        initialized in silc_schedule_init function.
157
158    SilcTaskQueue generic_queue
159
160        Task queue hook for generic tasks. This hook is reserved specificly
161        for generic tasks, tasks that apply to all file descriptors, except
162        to those that have specificly registered a non-timeout task. This hook
163        is also initialized in silc_schedule_init function.
164
165    SilcScheduleFd fd_list
166
167        List of file descriptors the scheduler is supposed to be listenning.
168        This is updated internally.
169
170    SilcUInt32 max_fd
171    SilcUInt32 last_fd
172
173        Size of the fd_list list. There can be `max_fd' many tasks in
174        the scheduler at once. The `last_fd' is the last valid entry
175        in the fd_list.
176
177    struct timeval *timeout;
178
179        Pointer to the schedules next timeout. Value of this timeout is
180        automatically updated in the silc_schedule function.
181
182    bool valid
183
184        Marks validity of the scheduler. This is a boolean value. When this
185        is false the scheduler is terminated and the program will end. This
186        set to true when the scheduler is initialized with silc_schedule_init
187        function.
188
189    fd_set in
190    fd_set out
191
192        File descriptor sets for select(). These are automatically managed
193        by the scheduler and should not be touched otherwise.
194
195    void *internal
196
197        System specific scheduler context.
198
199    SILC_MUTEX_DEFINE(lock)
200
201        Scheduler lock.
202
203    bool signal_tasks
204
205        TRUE when tasks has been registered from signals.  Next round in
206        scheduler will call the callbacks when this is TRUE.
207
208 */
209 struct SilcScheduleStruct {
210   void *app_context;            /* Application specific context */
211   SilcTaskQueue fd_queue;
212   SilcTaskQueue timeout_queue;
213   SilcTaskQueue generic_queue;
214   SilcScheduleFd fd_list;
215   SilcUInt32 max_fd;
216   SilcUInt32 last_fd;
217   struct timeval *timeout;
218   bool valid;
219   void *internal;
220   SILC_MUTEX_DEFINE(lock);
221   bool is_locked;
222   bool signal_tasks;
223 };
224
225 /* Initializes the scheduler. This returns the scheduler context that
226    is given as arugment usually to all silc_schedule_* functions.
227    The `max_tasks' indicates the number of maximum tasks that the
228    scheduler can handle. The `app_context' is application specific
229    context that is delivered to task callbacks. */
230
231 SilcSchedule silc_schedule_init(int max_tasks, void *app_context)
232 {
233   SilcSchedule schedule;
234
235   SILC_LOG_DEBUG(("Initializing scheduler"));
236
237   schedule = silc_calloc(1, sizeof(*schedule));
238
239   /* Allocate three task queues, one for file descriptor based tasks,
240      one for timeout tasks and one for generic tasks. */
241   silc_task_queue_alloc(&schedule->fd_queue);
242   silc_task_queue_alloc(&schedule->timeout_queue);
243   silc_task_queue_alloc(&schedule->generic_queue);
244
245   if (!max_tasks)
246     max_tasks = 200;
247
248   /* Initialize the scheduler */
249   schedule->fd_list = silc_calloc(max_tasks, sizeof(*schedule->fd_list));
250   schedule->max_fd = max_tasks;
251   schedule->timeout = NULL;
252   schedule->valid = TRUE;
253   schedule->app_context = app_context;
254
255   /* Allocate scheduler lock */
256   silc_mutex_alloc(&schedule->lock);
257
258   /* Initialize the platform specific scheduler. */
259   schedule->internal = silc_schedule_internal_init(schedule, app_context);
260
261   return schedule;
262 }
263
264 /* Uninitializes the schedule. This is called when the program is ready
265    to end. This removes all tasks and task queues. Returns FALSE if the
266    scheduler could not be uninitialized. This happens when the scheduler
267    is still valid and silc_schedule_stop has not been called. */
268
269 bool silc_schedule_uninit(SilcSchedule schedule)
270 {
271   SILC_LOG_DEBUG(("Uninitializing scheduler"));
272
273   if (schedule->valid == TRUE)
274     return FALSE;
275
276   /* Dispatch all timeouts before going away */
277   SILC_SCHEDULE_LOCK(schedule);
278   silc_mutex_lock(schedule->timeout_queue->lock);
279   silc_schedule_dispatch_timeout(schedule, TRUE);
280   silc_mutex_unlock(schedule->timeout_queue->lock);
281   SILC_SCHEDULE_UNLOCK(schedule);
282
283   /* Deliver signals before going away */
284   if (schedule->signal_tasks) {
285     silc_schedule_internal_signals_call(schedule->internal, schedule);
286     schedule->signal_tasks = FALSE;
287   }
288
289   /* Unregister all tasks */
290   silc_schedule_task_remove(schedule->fd_queue, SILC_ALL_TASKS);
291   silc_schedule_task_remove(schedule->timeout_queue, SILC_ALL_TASKS);
292   silc_schedule_task_remove(schedule->generic_queue, SILC_ALL_TASKS);
293
294   /* Unregister all task queues */
295   silc_task_queue_free(schedule->fd_queue);
296   silc_task_queue_free(schedule->timeout_queue);
297   silc_task_queue_free(schedule->generic_queue);
298
299   silc_free(schedule->fd_list);
300
301   /* Uninit the platform specific scheduler. */
302   silc_schedule_internal_uninit(schedule->internal);
303
304   silc_mutex_free(schedule->lock);
305   silc_free(schedule);
306
307   return TRUE;
308 }
309
310 /* Enlarge the capabilities of the scheduler to handle tasks to `max_tasks'. */
311
312 bool silc_schedule_reinit(SilcSchedule schedule, int max_tasks)
313 {
314   SILC_SCHEDULE_LOCK(schedule);
315   if (schedule->max_fd <= max_tasks)
316     return FALSE;
317   schedule->fd_list = silc_realloc(schedule->fd_list,
318                                    (sizeof(*schedule->fd_list) * max_tasks));
319   schedule->max_fd = max_tasks;
320   SILC_SCHEDULE_UNLOCK(schedule);
321   return TRUE;
322 }
323
324 /* Stops the schedule even if it is not supposed to be stopped yet.
325    After calling this, one should call silc_schedule_uninit (after the
326    silc_schedule has returned). */
327
328 void silc_schedule_stop(SilcSchedule schedule)
329 {
330   SILC_LOG_DEBUG(("Stopping scheduler"));
331   SILC_SCHEDULE_LOCK(schedule);
332   schedule->valid = FALSE;
333   SILC_SCHEDULE_UNLOCK(schedule);
334 }
335
336 /* Executes nontimeout tasks. It then checks whether any of ther fd tasks
337    was signaled by the silc_select. If some task was not signaled then
338    all generic tasks are executed for that task. The generic tasks are
339    never executed for task that has explicit fd task set. */
340 /* This holds the schedule->lock and the queue locks. */
341
342 static void silc_schedule_dispatch_nontimeout(SilcSchedule schedule)
343 {
344   SilcTask task;
345   int i;
346   SilcUInt32 fd, last_fd = schedule->last_fd;
347   SilcUInt16 revents;
348
349   for (i = 0; i <= last_fd; i++) {
350     if (schedule->fd_list[i].events == 0)
351       continue;
352
353     /* First check whether this fd has task in the fd queue */
354     silc_mutex_lock(schedule->fd_queue->lock);
355     fd = schedule->fd_list[i].fd;
356     task = silc_task_find(schedule->fd_queue, fd);
357     revents = schedule->fd_list[i].revents;
358
359     /* If the task was found then execute its callbacks. If not then
360        execute all generic tasks for that fd. */
361     if (task) {
362       /* Validity of the task is checked always before and after
363          execution beacuse the task might have been unregistered
364          in the callback function, ie. it is not valid anymore. */
365
366       /* Is the task ready for reading */
367       if (task->valid && revents & SILC_TASK_READ) {
368         silc_mutex_unlock(schedule->fd_queue->lock);
369         SILC_SCHEDULE_UNLOCK(schedule);
370         task->callback(schedule, schedule->app_context,
371                        SILC_TASK_READ, task->fd, task->context);
372         SILC_SCHEDULE_LOCK(schedule);
373         silc_mutex_lock(schedule->fd_queue->lock);
374       }
375
376       /* Is the task ready for writing */
377       if (task->valid && revents & SILC_TASK_WRITE) {
378         silc_mutex_unlock(schedule->fd_queue->lock);
379         SILC_SCHEDULE_UNLOCK(schedule);
380         task->callback(schedule, schedule->app_context,
381                        SILC_TASK_WRITE, task->fd, task->context);
382         SILC_SCHEDULE_LOCK(schedule);
383         silc_mutex_lock(schedule->fd_queue->lock);
384       }
385
386       if (!task->valid)
387         silc_schedule_task_remove(schedule->fd_queue, task);
388
389       silc_mutex_unlock(schedule->fd_queue->lock);
390     } else {
391       /* Run generic tasks for this fd. */
392
393       silc_mutex_unlock(schedule->fd_queue->lock);
394
395       silc_mutex_lock(schedule->generic_queue->lock);
396       if (!schedule->generic_queue->task) {
397         silc_mutex_unlock(schedule->generic_queue->lock);
398         continue;
399       }
400
401       task = schedule->generic_queue->task;
402       while(1) {
403         /* Validity of the task and fd is checked always before and after
404            execution beacuse the task might have been unregistered
405            in the callback function, ie. it is not valid anymore. */
406
407         /* Is the task ready for reading */
408         if (task->valid && revents & SILC_TASK_READ &&
409             fd == schedule->fd_list[i].fd) {
410           silc_mutex_unlock(schedule->generic_queue->lock);
411           SILC_SCHEDULE_UNLOCK(schedule);
412           task->callback(schedule, schedule->app_context,
413                          SILC_TASK_READ, fd, task->context);
414           SILC_SCHEDULE_LOCK(schedule);
415           silc_mutex_lock(schedule->generic_queue->lock);
416         }
417
418         /* Is the task ready for writing */
419         if (task->valid && revents & SILC_TASK_WRITE &&
420             fd == schedule->fd_list[i].fd) {
421           silc_mutex_unlock(schedule->generic_queue->lock);
422           SILC_SCHEDULE_UNLOCK(schedule);
423           task->callback(schedule, schedule->app_context,
424                          SILC_TASK_WRITE, fd, task->context);
425           SILC_SCHEDULE_LOCK(schedule);
426           silc_mutex_lock(schedule->generic_queue->lock);
427         }
428
429         if (!task->valid) {
430           /* Invalid (unregistered) tasks are removed from the
431              task queue. */
432           if (schedule->generic_queue->task == task->next) {
433             silc_schedule_task_remove(schedule->generic_queue, task);
434             silc_mutex_unlock(schedule->generic_queue->lock);
435             break;
436           }
437
438           task = task->next;
439           silc_schedule_task_remove(schedule->generic_queue, task);
440           continue;
441         }
442
443         /* Break if there isn't more tasks in the queue */
444         if (schedule->generic_queue->task == task->next)
445           break;
446
447         task = task->next;
448       }
449
450       silc_mutex_unlock(schedule->generic_queue->lock);
451     }
452   }
453 }
454
455 /* Executes all tasks whose timeout has expired. The task is removed from
456    the task queue after the callback function has returned. Also, invalid
457    tasks are removed here. We don't have to care about priorities because
458    tasks are already sorted in their priority order at the registration
459    phase. */
460 /* This holds the schedule->lock and the schedule->timeout_queue->lock */
461
462 static void silc_schedule_dispatch_timeout(SilcSchedule schedule,
463                                            bool dispatch_all)
464 {
465   SilcTaskQueue queue = schedule->timeout_queue;
466   SilcTask task;
467   struct timeval curtime;
468
469   SILC_LOG_DEBUG(("Running timeout tasks"));
470
471   silc_gettimeofday(&curtime);
472
473   queue = schedule->timeout_queue;
474   if (queue && queue->task) {
475     task = queue->task;
476
477     /* Walk thorugh all tasks in the particular task queue and run all
478        the expired tasks. */
479     while(1) {
480       /* Execute the task if the timeout has expired */
481       if (dispatch_all ||
482           silc_compare_timeval(&task->timeout, &curtime)) {
483         if (task->valid) {
484           silc_mutex_unlock(queue->lock);
485           SILC_SCHEDULE_UNLOCK(schedule);
486           task->callback(schedule, schedule->app_context,
487                          SILC_TASK_EXPIRE, task->fd, task->context);
488           SILC_SCHEDULE_LOCK(schedule);
489           silc_mutex_lock(queue->lock);
490         }
491
492         /* Break if there isn't more tasks in the queue */
493         if (queue->task == task->next) {
494           silc_schedule_task_remove(queue, task);
495           break;
496         }
497
498         task = task->next;
499
500         /* Remove the task from queue */
501         silc_schedule_task_remove(queue, task->prev);
502       } else {
503         /* The timeout hasn't expired, check for next one */
504
505         /* Break if there isn't more tasks in the queue */
506         if (queue->task == task->next)
507           break;
508
509         task = task->next;
510       }
511     }
512   }
513 }
514
515 /* Calculates next timeout for select(). This is the timeout value
516    when at earliest some of the timeout tasks expire. If this is in the
517    past, they will be run now. */
518 /* This holds the schedule->lock and the schedule->timeout_queue->lock */
519
520 static void silc_schedule_select_timeout(SilcSchedule schedule)
521 {
522   SilcTaskQueue queue = schedule->timeout_queue;
523   SilcTask task;
524   struct timeval curtime;
525
526   /* Get the current time */
527   silc_gettimeofday(&curtime);
528   schedule->timeout = NULL;
529
530   /* First task in the task queue has always the smallest timeout. */
531   task = queue->task;
532   while(1) {
533     if (task && task->valid == TRUE) {
534       /* If the timeout is in past, we will run the task and all other
535          timeout tasks from the past. */
536       if (silc_compare_timeval(&task->timeout, &curtime)) {
537         silc_schedule_dispatch_timeout(schedule, FALSE);
538
539         /* The task(s) has expired and doesn't exist on the task queue
540            anymore. We continue with new timeout. */
541         queue = schedule->timeout_queue;
542         task = queue->task;
543         if (task == NULL || task->valid == FALSE)
544           break;
545       }
546
547       /* Calculate the next timeout for select() */
548       queue->timeout.tv_sec = task->timeout.tv_sec - curtime.tv_sec;
549       queue->timeout.tv_usec = task->timeout.tv_usec - curtime.tv_usec;
550       if (queue->timeout.tv_sec < 0)
551         queue->timeout.tv_sec = 0;
552
553       /* We wouldn't want to go under zero, check for it. */
554       if (queue->timeout.tv_usec < 0) {
555         queue->timeout.tv_sec -= 1;
556         if (queue->timeout.tv_sec < 0)
557           queue->timeout.tv_sec = 0;
558         queue->timeout.tv_usec += 1000000L;
559       }
560
561       /* We've got the timeout value */
562       break;
563     } else {
564       /* Task is not valid, remove it and try next one. */
565       silc_schedule_task_remove(queue, task);
566       task = queue->task;
567       if (queue->task == NULL)
568         break;
569     }
570   }
571
572   /* Save the timeout */
573   if (task) {
574     schedule->timeout = &queue->timeout;
575     SILC_LOG_DEBUG(("timeout: sec=%d, usec=%d", schedule->timeout->tv_sec,
576                     schedule->timeout->tv_usec));
577   }
578 }
579
580 /* Runs the scheduler once and then returns. */
581
582 bool silc_schedule_one(SilcSchedule schedule, int timeout_usecs)
583 {
584   struct timeval timeout;
585   int ret;
586
587   SILC_LOG_DEBUG(("In scheduler loop"));
588
589   if (!schedule->is_locked)
590     SILC_SCHEDULE_LOCK(schedule);
591
592   /* Deliver signals if any has been set to be called */
593   if (schedule->signal_tasks) {
594     SILC_SCHEDULE_UNLOCK(schedule);
595     silc_schedule_internal_signals_call(schedule->internal, schedule);
596     schedule->signal_tasks = FALSE;
597     SILC_SCHEDULE_LOCK(schedule);
598   }
599
600   /* If the task queues aren't initialized or we aren't valid anymore
601      we will return */
602   if ((!schedule->fd_queue && !schedule->timeout_queue
603        && !schedule->generic_queue) || schedule->valid == FALSE) {
604     SILC_LOG_DEBUG(("Scheduler not valid anymore, exiting"));
605     if (!schedule->is_locked)
606       SILC_SCHEDULE_UNLOCK(schedule);
607     return FALSE;
608   }
609
610   /* Calculate next timeout for silc_select(). This is the timeout value
611      when at earliest some of the timeout tasks expire. */
612   silc_mutex_lock(schedule->timeout_queue->lock);
613   silc_schedule_select_timeout(schedule);
614   silc_mutex_unlock(schedule->timeout_queue->lock);
615
616   if (timeout_usecs >= 0) {
617     timeout.tv_sec = 0;
618     timeout.tv_usec = timeout_usecs;
619     schedule->timeout = &timeout;
620   }
621
622   SILC_SCHEDULE_UNLOCK(schedule);
623
624   /* This is the main select(). The program blocks here until some
625      of the selected file descriptors change status or the selected
626      timeout expires. */
627   SILC_LOG_DEBUG(("Select"));
628   ret = silc_select(schedule->fd_list, schedule->last_fd + 1,
629                     schedule->timeout);
630
631   SILC_SCHEDULE_LOCK(schedule);
632
633   switch (ret) {
634   case -1:
635     /* Error */
636     if (errno == EINTR)
637       break;
638     SILC_LOG_ERROR(("Error in select(): %s", strerror(errno)));
639     break;
640   case 0:
641     /* Timeout */
642     silc_mutex_lock(schedule->timeout_queue->lock);
643     silc_schedule_dispatch_timeout(schedule, FALSE);
644     silc_mutex_unlock(schedule->timeout_queue->lock);
645     break;
646   default:
647     /* There is some data available now */
648     SILC_LOG_DEBUG(("Running non-timeout tasks"));
649     silc_schedule_dispatch_nontimeout(schedule);
650     break;
651   }
652
653   if (!schedule->is_locked)
654     SILC_SCHEDULE_UNLOCK(schedule);
655
656   return TRUE;
657 }
658
659 /* The SILC scheduler. This is actually the main routine in SILC programs.
660    When this returns the program is to be ended. Before this function can
661    be called, one must call silc_schedule_init function. */
662
663 void silc_schedule(SilcSchedule schedule)
664 {
665   SILC_LOG_DEBUG(("Running scheduler"));
666
667   if (schedule->valid == FALSE) {
668     SILC_LOG_ERROR(("Scheduler is not valid, stopping"));
669     return;
670   }
671
672   SILC_SCHEDULE_LOCK(schedule);
673   schedule->is_locked = TRUE;
674
675   /* Start the scheduler loop */
676   while (silc_schedule_one(schedule, -1))
677     ;
678
679   SILC_SCHEDULE_UNLOCK(schedule);
680 }
681
682 /* Wakes up the scheduler. This is used only in multi-threaded
683    environments where threads may add new tasks or remove old tasks
684    from task queues. This is called to wake up the scheduler in the
685    main thread so that it detects the changes in the task queues.
686    If threads support is not compiled in this function has no effect.
687    Implementation of this function is platform specific. */
688
689 void silc_schedule_wakeup(SilcSchedule schedule)
690 {
691 #ifdef SILC_THREADS
692   SILC_LOG_DEBUG(("Wakeup scheduler"));
693   SILC_SCHEDULE_LOCK(schedule);
694   silc_schedule_internal_wakeup(schedule->internal);
695   SILC_SCHEDULE_UNLOCK(schedule);
696 #endif
697 }
698
699 /* Returns the application specific context that was saved into the
700    scheduler in silc_schedule_init function.  The context is also
701    returned to application in task callback functions, but this function
702    may be used to get it as well if needed. */
703
704 void *silc_schedule_get_context(SilcSchedule schedule)
705 {
706   return schedule->app_context;
707 }
708
709 /* Add new task to the scheduler */
710
711 SilcTask silc_schedule_task_add(SilcSchedule schedule, SilcUInt32 fd,
712                                 SilcTaskCallback callback, void *context,
713                                 long seconds, long useconds,
714                                 SilcTaskType type,
715                                 SilcTaskPriority priority)
716 {
717   SilcTask newtask;
718   SilcTaskQueue queue;
719   int timeout = FALSE;
720
721   if (!schedule->valid)
722     return NULL;
723
724   queue = SILC_SCHEDULE_GET_QUEUE(type);
725
726   /* If the task is generic task, we check whether this task has already
727      been registered. Generic tasks are registered only once and after that
728      the same task applies to all file descriptors to be registered. */
729   if (type == SILC_TASK_GENERIC) {
730     silc_mutex_lock(queue->lock);
731
732     SILC_LOG_DEBUG(("Registering new task, fd=%d type=%d priority=%d", fd,
733                     type, priority));
734
735     if (queue->task) {
736       SilcTask task = queue->task;
737       while(1) {
738         if ((task->callback == callback) && (task->context == context)) {
739           SILC_LOG_DEBUG(("Found matching generic task, using the match"));
740
741           silc_mutex_unlock(queue->lock);
742
743           /* Add the fd to be listened, the task found now applies to this
744              fd as well. */
745           silc_schedule_set_listen_fd(schedule, fd, SILC_TASK_READ, FALSE);
746           return task;
747         }
748
749         if (queue->task == task->next)
750           break;
751
752         task = task->next;
753       }
754     }
755
756     silc_mutex_unlock(queue->lock);
757   }
758
759   newtask = silc_calloc(1, sizeof(*newtask));
760   if (!newtask)
761     return NULL;
762
763   SILC_LOG_DEBUG(("Registering new task %p, fd=%d type=%d priority=%d",
764                   newtask, fd, type, priority));
765
766   newtask->fd = fd;
767   newtask->context = context;
768   newtask->callback = callback;
769   newtask->valid = TRUE;
770   newtask->priority = priority;
771   newtask->type = type;
772   newtask->next = newtask;
773   newtask->prev = newtask;
774
775   /* Create timeout if marked to be timeout task */
776   if (((seconds + useconds) > 0) && (type == SILC_TASK_TIMEOUT)) {
777     silc_gettimeofday(&newtask->timeout);
778     newtask->timeout.tv_sec += seconds + (useconds / 1000000L);
779     newtask->timeout.tv_usec += (useconds % 1000000L);
780     if (newtask->timeout.tv_usec > 999999L) {
781       newtask->timeout.tv_sec += 1;
782       newtask->timeout.tv_usec -= 1000000L;
783     }
784     timeout = TRUE;
785   }
786
787   /* If the task is non-timeout task we have to tell the scheduler that we
788      would like to have these tasks scheduled at some odd distant future. */
789   if (type != SILC_TASK_TIMEOUT)
790     silc_schedule_set_listen_fd(schedule, fd, SILC_TASK_READ, FALSE);
791
792   silc_mutex_lock(queue->lock);
793
794   /* Is this first task of the queue? */
795   if (queue->task == NULL) {
796     queue->task = newtask;
797     silc_mutex_unlock(queue->lock);
798     return newtask;
799   }
800
801   if (timeout)
802     newtask = silc_task_add_timeout(queue, newtask, priority);
803   else
804     newtask = silc_task_add(queue, newtask, priority);
805
806   silc_mutex_unlock(queue->lock);
807
808   return newtask;
809 }
810
811 /* Removes a task from the scheduler */
812
813 void silc_schedule_task_del(SilcSchedule schedule, SilcTask task)
814 {
815   SilcTaskQueue queue = SILC_SCHEDULE_GET_QUEUE(task->type);
816
817   /* Unregister all tasks */
818   if (task == SILC_ALL_TASKS) {
819     SilcTask next;
820     SILC_LOG_DEBUG(("Unregistering all tasks at once"));
821
822     silc_mutex_lock(queue->lock);
823
824     if (!queue->task) {
825       silc_mutex_unlock(queue->lock);
826       return;
827     }
828
829     next = queue->task;
830
831     while(1) {
832       if (next->valid)
833         next->valid = FALSE;
834       if (queue->task == next->next)
835         break;
836       next = next->next;
837     }
838
839     silc_mutex_unlock(queue->lock);
840     return;
841   }
842
843   SILC_LOG_DEBUG(("Unregistering task"));
844
845   silc_mutex_lock(queue->lock);
846
847   /* Unregister the specific task */
848   if (task->valid)
849     task->valid = FALSE;
850
851   silc_mutex_unlock(queue->lock);
852 }
853
854 /* Remove task by fd */
855
856 void silc_schedule_task_del_by_fd(SilcSchedule schedule, SilcUInt32 fd)
857 {
858   SILC_LOG_DEBUG(("Unregister task by fd %d", fd));
859
860   silc_task_del_by_fd(schedule->timeout_queue, fd);
861   silc_task_del_by_fd(schedule->fd_queue, fd);
862 }
863
864 /* Remove task by task callback. */
865
866 void silc_schedule_task_del_by_callback(SilcSchedule schedule,
867                                         SilcTaskCallback callback)
868 {
869   SILC_LOG_DEBUG(("Unregister task by callback"));
870
871   silc_task_del_by_callback(schedule->timeout_queue, callback);
872   silc_task_del_by_callback(schedule->fd_queue, callback);
873   silc_task_del_by_callback(schedule->generic_queue, callback);
874 }
875
876 /* Remove task by context. */
877
878 void silc_schedule_task_del_by_context(SilcSchedule schedule, void *context)
879 {
880   SILC_LOG_DEBUG(("Unregister task by context"));
881
882   silc_task_del_by_context(schedule->timeout_queue, context);
883   silc_task_del_by_context(schedule->fd_queue, context);
884   silc_task_del_by_context(schedule->generic_queue, context);
885 }
886
887 /* Sets a file descriptor to be listened by select() in scheduler. One can
888    call this directly if wanted. This can be called multiple times for
889    one file descriptor to set different iomasks. */
890
891 void silc_schedule_set_listen_fd(SilcSchedule schedule, SilcUInt32 fd,
892                                  SilcTaskEvent mask, bool send_events)
893 {
894   int i;
895   bool found = FALSE;
896
897   if (!schedule->valid)
898     return;
899
900   SILC_SCHEDULE_LOCK(schedule);
901
902   for (i = 0; i < schedule->max_fd; i++)
903     if (schedule->fd_list[i].fd == fd) {
904       schedule->fd_list[i].fd = fd;
905       schedule->fd_list[i].events = mask;
906       schedule->fd_list[i].revents = 0;
907       if (i > schedule->last_fd)
908         schedule->last_fd = i;
909       found = TRUE;
910       if (send_events) {
911         schedule->fd_list[i].revents = mask;
912         silc_schedule_dispatch_nontimeout(schedule);
913       }
914       break;
915     }
916
917   if (!found)
918     for (i = 0; i < schedule->max_fd; i++)
919       if (schedule->fd_list[i].events == 0) {
920         schedule->fd_list[i].fd = fd;
921         schedule->fd_list[i].events = mask;
922         schedule->fd_list[i].revents = 0;
923         if (i > schedule->last_fd)
924           schedule->last_fd = i;
925         if (send_events) {
926           schedule->fd_list[i].revents = mask;
927           silc_schedule_dispatch_nontimeout(schedule);
928         }
929         break;
930       }
931
932   SILC_SCHEDULE_UNLOCK(schedule);
933 }
934
935 /* Removes a file descriptor from listen list. */
936
937 void silc_schedule_unset_listen_fd(SilcSchedule schedule, SilcUInt32 fd)
938 {
939   int i;
940
941   SILC_SCHEDULE_LOCK(schedule);
942
943   SILC_LOG_DEBUG(("Unset listen fd %d", fd));
944
945   for (i = 0; i < schedule->max_fd; i++)
946     if (schedule->fd_list[i].fd == fd) {
947       schedule->fd_list[i].fd = 0;
948       schedule->fd_list[i].events = 0;
949       schedule->fd_list[i].revents = 0;
950       if (schedule->last_fd == i && i > 0)
951         schedule->last_fd = i - 1;
952       break;
953     }
954
955   SILC_SCHEDULE_UNLOCK(schedule);
956 }
957
958 /* Register a new signal */
959
960 void silc_schedule_signal_register(SilcSchedule schedule, SilcUInt32 signal,
961                                    SilcTaskCallback callback, void *context)
962 {
963   silc_schedule_internal_signal_register(schedule->internal, signal,
964                                          callback, context);
965 }
966
967 /* Unregister a new signal */
968
969 void silc_schedule_signal_unregister(SilcSchedule schedule, SilcUInt32 signal,
970                                      SilcTaskCallback callback, void *context)
971 {
972   silc_schedule_internal_signal_unregister(schedule->internal, signal,
973                                            callback, context);
974 }
975
976 /* Call signal indicated by `signal'. */
977
978 void silc_schedule_signal_call(SilcSchedule schedule, SilcUInt32 signal)
979 {
980   /* Mark that signals needs to be delivered later. */
981   silc_schedule_internal_signal_call(schedule->internal, signal);
982   schedule->signal_tasks = TRUE;
983 }
984
985 /* Allocates a newtask task queue into the scheduler */
986
987 static void silc_task_queue_alloc(SilcTaskQueue *queue)
988 {
989   *queue = silc_calloc(1, sizeof(**queue));
990   silc_mutex_alloc(&(*queue)->lock);
991 }
992
993 /* Free's a task queue. */
994
995 static void silc_task_queue_free(SilcTaskQueue queue)
996 {
997   silc_mutex_free(queue->lock);
998   memset(queue, 'F', sizeof(*queue));
999   silc_free(queue);
1000 }
1001
1002 /* Return task by its fd. */
1003
1004 static SilcTask silc_task_find(SilcTaskQueue queue, SilcUInt32 fd)
1005 {
1006   SilcTask next;
1007
1008   if (!queue->task)
1009     return NULL;
1010
1011   next = queue->task;
1012
1013   while (1) {
1014     if (next->fd == fd)
1015       return next;
1016     if (queue->task == next->next)
1017       return NULL;
1018     next = next->next;
1019   }
1020
1021   return NULL;
1022 }
1023
1024 /* Adds a non-timeout task into the task queue. This function is used
1025    by silc_task_register function. Returns a pointer to the registered
1026    task. */
1027
1028 static SilcTask silc_task_add(SilcTaskQueue queue, SilcTask newtask,
1029                               SilcTaskPriority priority)
1030 {
1031   SilcTask task, next, prev;
1032
1033   /* Take the first task in the queue */
1034   task = queue->task;
1035
1036   switch(priority) {
1037   case SILC_TASK_PRI_LOW:
1038     /* Lowest priority. The task is added at the end of the list. */
1039     prev = task->prev;
1040     newtask->prev = prev;
1041     newtask->next = task;
1042     prev->next = newtask;
1043     task->prev = newtask;
1044     break;
1045   case SILC_TASK_PRI_NORMAL:
1046     /* Normal priority. The task is added before lower priority tasks
1047        but after tasks with higher priority. */
1048     prev = task->prev;
1049     while(prev != task) {
1050       if (prev->priority > SILC_TASK_PRI_LOW)
1051         break;
1052       prev = prev->prev;
1053     }
1054     if (prev == task) {
1055       /* There are only lower priorities in the list, we will
1056          sit before them and become the first task in the queue. */
1057       prev = task->prev;
1058       newtask->prev = prev;
1059       newtask->next = task;
1060       task->prev = newtask;
1061       prev->next = newtask;
1062
1063       /* We are now the first task in queue */
1064       queue->task = newtask;
1065     } else {
1066       /* Found a spot from the list, add the task to the list. */
1067       next = prev->next;
1068       newtask->prev = prev;
1069       newtask->next = next;
1070       prev->next = newtask;
1071       next->prev = newtask;
1072     }
1073     break;
1074   default:
1075     silc_free(newtask);
1076     return NULL;
1077   }
1078
1079   return newtask;
1080 }
1081
1082 /* Return the timeout task with smallest timeout. */
1083
1084 static SilcTask silc_task_get_first(SilcTaskQueue queue, SilcTask first)
1085 {
1086   SilcTask prev, task;
1087
1088   prev = first->prev;
1089
1090   if (first == prev)
1091     return first;
1092
1093   task = first;
1094   while (1) {
1095     if (first == prev)
1096       break;
1097
1098     if (silc_compare_timeval(&prev->timeout, &task->timeout))
1099       task = prev;
1100
1101     prev = prev->prev;
1102   }
1103
1104   return task;
1105 }
1106
1107 /* Adds a timeout task into the task queue. This function is used by
1108    silc_task_register function. Returns a pointer to the registered
1109    task. Timeout tasks are sorted by their timeout value in ascending
1110    order. The priority matters if there are more than one task with
1111    same timeout. */
1112
1113 static SilcTask silc_task_add_timeout(SilcTaskQueue queue, SilcTask newtask,
1114                                       SilcTaskPriority priority)
1115 {
1116   SilcTask task, prev, next;
1117
1118   /* Take the first task in the queue */
1119   task = queue->task;
1120
1121   /* Take last task from the list */
1122   prev = task->prev;
1123
1124   switch(priority) {
1125   case SILC_TASK_PRI_LOW:
1126     /* Lowest priority. The task is added at the end of the list. */
1127     while(prev != task) {
1128
1129       /* If we have longer timeout than with the task head of us
1130          we have found our spot. */
1131       if (silc_compare_timeval(&prev->timeout, &newtask->timeout))
1132         break;
1133
1134       /* If we are equal size of timeout we will be after it. */
1135       if (!silc_compare_timeval(&newtask->timeout, &prev->timeout))
1136         break;
1137
1138       /* We have shorter timeout, compare to next one. */
1139       prev = prev->prev;
1140     }
1141     /* Found a spot from the list, add the task to the list. */
1142     next = prev->next;
1143     newtask->prev = prev;
1144     newtask->next = next;
1145     prev->next = newtask;
1146     next->prev = newtask;
1147
1148     if (prev == task) {
1149       /* Check if we are going to be the first task in the queue */
1150       if (silc_compare_timeval(&prev->timeout, &newtask->timeout))
1151         break;
1152       if (!silc_compare_timeval(&newtask->timeout, &prev->timeout))
1153         break;
1154
1155       /* We are now the first task in queue */
1156       queue->task = newtask;
1157     }
1158     break;
1159   case SILC_TASK_PRI_NORMAL:
1160     /* Normal priority. The task is added before lower priority tasks
1161        but after tasks with higher priority. */
1162     while(prev != task) {
1163
1164       /* If we have longer timeout than with the task head of us
1165          we have found our spot. */
1166       if (silc_compare_timeval(&prev->timeout, &newtask->timeout))
1167         break;
1168
1169       /* If we are equal size of timeout, priority kicks in place. */
1170       if (!silc_compare_timeval(&newtask->timeout, &prev->timeout))
1171         if (prev->priority >= SILC_TASK_PRI_NORMAL)
1172           break;
1173
1174       /* We have shorter timeout or higher priority, compare to next one. */
1175       prev = prev->prev;
1176     }
1177     /* Found a spot from the list, add the task to the list. */
1178     next = prev->next;
1179     newtask->prev = prev;
1180     newtask->next = next;
1181     prev->next = newtask;
1182     next->prev = newtask;
1183
1184     if (prev == task) {
1185       /* Check if we are going to be the first task in the queue */
1186       if (silc_compare_timeval(&prev->timeout, &newtask->timeout))
1187         break;
1188       if (!silc_compare_timeval(&newtask->timeout, &prev->timeout))
1189         if (prev->priority >= SILC_TASK_PRI_NORMAL)
1190           break;
1191
1192       /* We are now the first task in queue */
1193       queue->task = newtask;
1194     }
1195     break;
1196   default:
1197     silc_free(newtask);
1198     return NULL;
1199   }
1200
1201   return newtask;
1202 }
1203
1204 /* Removes (unregisters) a task from particular task queue. This function
1205    is used internally by scheduler. This must be called holding the
1206    queue->lock. */
1207
1208 static int silc_schedule_task_remove(SilcTaskQueue queue, SilcTask task)
1209 {
1210   SilcTask first, old, next;
1211
1212   if (!queue || !task)
1213     return FALSE;
1214
1215   if (!queue->task) {
1216     return FALSE;
1217   }
1218
1219   first = queue->task;
1220
1221   /* Unregister all tasks in queue */
1222   if (task == SILC_ALL_TASKS) {
1223     SILC_LOG_DEBUG(("Removing all tasks at once"));
1224     next = first;
1225
1226     while(1) {
1227       old = next->next;
1228       silc_free(next);
1229       if (old == first)
1230         break;
1231       next = old;
1232     }
1233
1234     queue->task = NULL;
1235     return TRUE;
1236   }
1237
1238   SILC_LOG_DEBUG(("Removing task %p", task));
1239
1240   /* Unregister the task */
1241   old = first;
1242   while(1) {
1243     if (old == task) {
1244       SilcTask prev, next;
1245
1246       prev = old->prev;
1247       next = old->next;
1248       prev->next = next;
1249       next->prev = prev;
1250
1251       if (prev == old && next == old)
1252         queue->task = NULL;
1253       if (queue->task == old)
1254         queue->task = silc_task_get_first(queue, next);
1255
1256       silc_free(old);
1257       return TRUE;
1258     }
1259     old = old->prev;
1260
1261     if (old == first) {
1262       return FALSE;
1263     }
1264   }
1265 }
1266
1267 static void silc_task_del_by_fd(SilcTaskQueue queue, SilcUInt32 fd)
1268 {
1269   SilcTask next;
1270
1271   silc_mutex_lock(queue->lock);
1272
1273   if (!queue->task) {
1274     silc_mutex_unlock(queue->lock);
1275     return;
1276   }
1277
1278   next = queue->task;
1279
1280   while(1) {
1281     if (next->fd == fd)
1282       next->valid = FALSE;
1283     if (queue->task == next->next)
1284       break;
1285     next = next->next;
1286   }
1287
1288   silc_mutex_unlock(queue->lock);
1289 }
1290
1291 static void silc_task_del_by_callback(SilcTaskQueue queue,
1292                                       SilcTaskCallback callback)
1293 {
1294   SilcTask next;
1295
1296   silc_mutex_lock(queue->lock);
1297
1298   if (!queue->task) {
1299     silc_mutex_unlock(queue->lock);
1300     return;
1301   }
1302
1303   next = queue->task;
1304
1305   while(1) {
1306     if (next->callback == callback)
1307       next->valid = FALSE;
1308     if (queue->task == next->next)
1309       break;
1310     next = next->next;
1311   }
1312
1313   silc_mutex_unlock(queue->lock);
1314 }
1315
1316 static void silc_task_del_by_context(SilcTaskQueue queue, void *context)
1317 {
1318   SilcTask next;
1319
1320   silc_mutex_lock(queue->lock);
1321
1322   if (!queue->task) {
1323     silc_mutex_unlock(queue->lock);
1324     return;
1325   }
1326
1327   next = queue->task;
1328
1329   while(1) {
1330     if (next->context == context)
1331       next->valid = FALSE;
1332     if (queue->task == next->next)
1333       break;
1334     next = next->next;
1335   }
1336
1337   silc_mutex_unlock(queue->lock);
1338 }