Call to set_wakeup added after tasks added/removed to/from pending_timeout
[oweals/gnunet.git] / src / util / scheduler.c
1 /*
2       This file is part of GNUnet
3       Copyright (C) 2009-2017 GNUnet e.V.
4
5       GNUnet is free software; you can redistribute it and/or modify
6       it under the terms of the GNU General Public License as published
7       by the Free Software Foundation; either version 3, or (at your
8       option) any later version.
9
10       GNUnet is distributed in the hope that it will be useful, but
11       WITHOUT ANY WARRANTY; without even the implied warranty of
12       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13       General Public License for more details.
14
15       You should have received a copy of the GNU General Public License
16       along with GNUnet; see the file COPYING.  If not, write to the
17       Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18       Boston, MA 02110-1301, USA.
19  */
20 /**
21  * @file util/scheduler.c
22  * @brief schedule computations using continuation passing style
23  * @author Christian Grothoff
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.h"
27 #include "disk.h"
28
29 #define LOG(kind,...) GNUNET_log_from (kind, "util-scheduler", __VA_ARGS__)
30
31 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-scheduler", syscall)
32
33
34 #if HAVE_EXECINFO_H
35 #include "execinfo.h"
36
37 /**
38  * Use lsof to generate file descriptor reports on select error?
39  * (turn off for stable releases).
40  */
41 #define USE_LSOF GNUNET_NO
42
43 /**
44  * Obtain trace information for all scheduler calls that schedule tasks.
45  */
46 #define EXECINFO GNUNET_NO
47
48 /**
49  * Check each file descriptor before adding
50  */
51 #define DEBUG_FDS GNUNET_NO
52
53 /**
54  * Depth of the traces collected via EXECINFO.
55  */
56 #define MAX_TRACE_DEPTH 50
57 #endif
58
59 /**
60  * Should we figure out which tasks are delayed for a while
61  * before they are run? (Consider using in combination with EXECINFO).
62  */
63 #define PROFILE_DELAYS GNUNET_NO
64
65 /**
66  * Task that were in the queue for longer than this are reported if
67  * PROFILE_DELAYS is active.
68  */
69 #define DELAY_THRESHOLD GNUNET_TIME_UNIT_SECONDS
70
71
72 /**
73  * Argument to be passed from the driver to
74  * #GNUNET_SCHEDULER_run_from_driver().  Contains the
75  * scheduler's internal state.
76  */
77 struct GNUNET_SCHEDULER_Handle
78 {
79   /**
80    * Passed here to avoid constantly allocating/deallocating
81    * this element, but generally we want to get rid of this.
82    * @deprecated
83    */
84   struct GNUNET_NETWORK_FDSet *rs;
85
86   /**
87    * Passed here to avoid constantly allocating/deallocating
88    * this element, but generally we want to get rid of this.
89    * @deprecated
90    */
91   struct GNUNET_NETWORK_FDSet *ws;
92
93   /**
94    * Driver we used for the event loop.
95    */
96   const struct GNUNET_SCHEDULER_Driver *driver;
97
98 };
99
100
101 /**
102  * Entry in list of pending tasks.
103  */
104 struct GNUNET_SCHEDULER_Task
105 {
106   /**
107    * This is a linked list.
108    */
109   struct GNUNET_SCHEDULER_Task *next;
110
111   /**
112    * This is a linked list.
113    */
114   struct GNUNET_SCHEDULER_Task *prev;
115
116   /**
117    * Function to run when ready.
118    */
119   GNUNET_SCHEDULER_TaskCallback callback;
120
121   /**
122    * Closure for the @e callback.
123    */
124   void *callback_cls;
125
126   /**
127    * Handle to the scheduler's state.
128    */
129   const struct GNUNET_SCHEDULER_Handle *sh;
130
131   /**
132    * Set of file descriptors this task is waiting
133    * for for reading.  Once ready, this is updated
134    * to reflect the set of file descriptors ready
135    * for operation.
136    */
137   struct GNUNET_NETWORK_FDSet *read_set;
138
139   /**
140    * Set of file descriptors this task is waiting for for writing.
141    * Once ready, this is updated to reflect the set of file
142    * descriptors ready for operation.
143    */
144   struct GNUNET_NETWORK_FDSet *write_set;
145
146   /**
147    * Information about which FDs are ready for this task (and why).
148    */
149   const struct GNUNET_SCHEDULER_FdInfo *fds;
150
151   /**
152    * Storage location used for @e fds if we want to avoid
153    * a separate malloc() call in the common case that this
154    * task is only about a single FD.
155    */
156   struct GNUNET_SCHEDULER_FdInfo fdx;
157
158   /**
159    * Absolute timeout value for the task, or
160    * #GNUNET_TIME_UNIT_FOREVER_ABS for "no timeout".
161    */
162   struct GNUNET_TIME_Absolute timeout;
163
164 #if PROFILE_DELAYS
165   /**
166    * When was the task scheduled?
167    */
168   struct GNUNET_TIME_Absolute start_time;
169 #endif
170
171   /**
172    * Size of the @e fds array.
173    */
174   unsigned int fds_len;
175
176   /**
177    * Why is the task ready?  Set after task is added to ready queue.
178    * Initially set to zero.  All reasons that have already been
179    * satisfied (i.e.  read or write ready) will be set over time.
180    */
181   enum GNUNET_SCHEDULER_Reason reason;
182
183   /**
184    * Task priority.
185    */
186   enum GNUNET_SCHEDULER_Priority priority;
187
188   /**
189    * Set if we only wait for reading from a single FD, otherwise -1.
190    */
191   int read_fd;
192
193   /**
194    * Set if we only wait for writing to a single FD, otherwise -1.
195    */
196   int write_fd;
197
198   /**
199    * Should the existence of this task in the queue be counted as
200    * reason to not shutdown the scheduler?
201    */
202   int lifeness;
203
204   /**
205    * Is this task run on shutdown?
206    */
207   int on_shutdown;
208
209   /**
210    * Is this task in the ready list?
211    */
212   int in_ready_list;
213
214 #if EXECINFO
215   /**
216    * Array of strings which make up a backtrace from the point when this
217    * task was scheduled (essentially, who scheduled the task?)
218    */
219   char **backtrace_strings;
220
221   /**
222    * Size of the backtrace_strings array
223    */
224   int num_backtrace_strings;
225 #endif
226
227
228 };
229
230 /**
231  * The driver used for the event loop. Will be handed over to
232  * the scheduler in #GNUNET_SCHEDULER_run_from_driver(), peristed
233  * there in this variable for later use in functions like
234  * #GNUNET_SCHEDULER_add_select(), #add_without_sets() and
235  * #GNUNET_SCHEDULER_cancel().
236  */
237 static const struct GNUNET_SCHEDULER_Driver *scheduler_driver;
238
239 /**
240  * Head of list of tasks waiting for an event.
241  */
242 static struct GNUNET_SCHEDULER_Task *pending_head;
243
244 /**
245  * Tail of list of tasks waiting for an event.
246  */
247 static struct GNUNET_SCHEDULER_Task *pending_tail;
248
249 /**
250  * Head of list of tasks waiting for shutdown.
251  */
252 static struct GNUNET_SCHEDULER_Task *shutdown_head;
253
254 /**
255  * Tail of list of tasks waiting for shutdown.
256  */
257 static struct GNUNET_SCHEDULER_Task *shutdown_tail;
258
259 /**
260  * List of tasks waiting ONLY for a timeout event.
261  * Sorted by timeout (earliest first).  Used so that
262  * we do not traverse the list of these tasks when
263  * building select sets (we just look at the head
264  * to determine the respective timeout ONCE).
265  */
266 static struct GNUNET_SCHEDULER_Task *pending_timeout_head;
267
268 /**
269  * List of tasks waiting ONLY for a timeout event.
270  * Sorted by timeout (earliest first).  Used so that
271  * we do not traverse the list of these tasks when
272  * building select sets (we just look at the head
273  * to determine the respective timeout ONCE).
274  */
275 static struct GNUNET_SCHEDULER_Task *pending_timeout_tail;
276
277 /**
278  * Last inserted task waiting ONLY for a timeout event.
279  * Used to (heuristically) speed up insertion.
280  */
281 static struct GNUNET_SCHEDULER_Task *pending_timeout_last;
282
283 /**
284  * ID of the task that is running right now.
285  */
286 static struct GNUNET_SCHEDULER_Task *active_task;
287
288 /**
289  * Head of list of tasks ready to run right now, grouped by importance.
290  */
291 static struct GNUNET_SCHEDULER_Task *ready_head[GNUNET_SCHEDULER_PRIORITY_COUNT];
292
293 /**
294  * Tail of list of tasks ready to run right now, grouped by importance.
295  */
296 static struct GNUNET_SCHEDULER_Task *ready_tail[GNUNET_SCHEDULER_PRIORITY_COUNT];
297
298 /**
299  * Number of tasks on the ready list.
300  */
301 static unsigned int ready_count;
302
303 /**
304  * How many tasks have we run so far?
305  */
306 static unsigned long long tasks_run;
307
308 /**
309  * Priority of the task running right now.  Only
310  * valid while a task is running.
311  */
312 static enum GNUNET_SCHEDULER_Priority current_priority;
313
314 /**
315  * Priority of the highest task added in the current select
316  * iteration.
317  */
318 static enum GNUNET_SCHEDULER_Priority max_priority_added;
319
320 /**
321  * Value of the 'lifeness' flag for the current task.
322  */
323 static int current_lifeness;
324
325 /**
326  * Function to use as a select() in the scheduler.
327  * If NULL, we use GNUNET_NETWORK_socket_select().
328  */
329 static GNUNET_SCHEDULER_select scheduler_select;
330
331 /**
332  * Task context of the current task.
333  */
334 static struct GNUNET_SCHEDULER_TaskContext tc;
335
336 /**
337  * Closure for #scheduler_select.
338  */
339 static void *scheduler_select_cls;
340
341
342 /**
343  * Sets the select function to use in the scheduler (scheduler_select).
344  *
345  * @param new_select new select function to use
346  * @param new_select_cls closure for @a new_select
347  * @return previously used select function, NULL for default
348  */
349 void
350 GNUNET_SCHEDULER_set_select (GNUNET_SCHEDULER_select new_select,
351                              void *new_select_cls)
352 {
353   scheduler_select = new_select;
354   scheduler_select_cls = new_select_cls;
355 }
356
357
358 /**
359  * Check that the given priority is legal (and return it).
360  *
361  * @param p priority value to check
362  * @return p on success, 0 on error
363  */
364 static enum GNUNET_SCHEDULER_Priority
365 check_priority (enum GNUNET_SCHEDULER_Priority p)
366 {
367   if ((p >= 0) && (p < GNUNET_SCHEDULER_PRIORITY_COUNT))
368     return p;
369   GNUNET_assert (0);
370   return 0;                     /* make compiler happy */
371 }
372
373
374 /**
375  * Update all sets and timeout for select.
376  *
377  * @param rs read-set, set to all FDs we would like to read (updated)
378  * @param ws write-set, set to all FDs we would like to write (updated)
379  * @param timeout next timeout (updated)
380  */
381 void getNextPendingTimeout(struct GNUNET_TIME_Relative *timeout)
382 {
383
384   struct GNUNET_SCHEDULER_Task *pos;
385   struct GNUNET_TIME_Absolute now;
386   struct GNUNET_TIME_Relative to;
387
388   now = GNUNET_TIME_absolute_get ();
389   pos = pending_timeout_head;
390   if (NULL != pos)
391   {
392     to = GNUNET_TIME_absolute_get_difference (now, pos->timeout);
393     if (timeout->rel_value_us > to.rel_value_us)
394       *timeout = to;
395     if (0 != pos->reason)
396       *timeout = GNUNET_TIME_UNIT_ZERO;
397   }
398 }
399
400 static void
401 update_sets (struct GNUNET_NETWORK_FDSet *rs,
402              struct GNUNET_NETWORK_FDSet *ws,
403              struct GNUNET_TIME_Relative *timeout)
404 {
405   struct GNUNET_SCHEDULER_Task *pos;
406   struct GNUNET_TIME_Absolute now;
407   struct GNUNET_TIME_Relative to;
408
409   now = GNUNET_TIME_absolute_get ();
410
411   getNextPendingTimeout(timeout);
412   for (pos = pending_head; NULL != pos; pos = pos->next)
413   {
414     if (pos->timeout.abs_value_us != GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
415     {
416       to = GNUNET_TIME_absolute_get_difference (now, pos->timeout);
417       if (timeout->rel_value_us > to.rel_value_us)
418         *timeout = to;
419     }
420     if (-1 != pos->read_fd)
421       GNUNET_NETWORK_fdset_set_native (rs, pos->read_fd);
422     if (-1 != pos->write_fd)
423       GNUNET_NETWORK_fdset_set_native (ws, pos->write_fd);
424     if (NULL != pos->read_set)
425       GNUNET_NETWORK_fdset_add (rs, pos->read_set);
426     if (NULL != pos->write_set)
427       GNUNET_NETWORK_fdset_add (ws, pos->write_set);
428     if (0 != pos->reason)
429       *timeout = GNUNET_TIME_UNIT_ZERO;
430   }
431 }
432
433
434 /**
435  * Check if the ready set overlaps with the set we want to have ready.
436  * If so, update the want set (set all FDs that are ready).  If not,
437  * return #GNUNET_NO.
438  *
439  * @param ready set that is ready
440  * @param want set that we want to be ready
441  * @return #GNUNET_YES if there was some overlap
442  */
443 static int
444 set_overlaps (const struct GNUNET_NETWORK_FDSet *ready,
445               struct GNUNET_NETWORK_FDSet *want)
446 {
447   if ((NULL == want) || (NULL == ready))
448     return GNUNET_NO;
449   if (GNUNET_NETWORK_fdset_overlap (ready, want))
450   {
451     /* copy all over (yes, there maybe unrelated bits,
452      * but this should not hurt well-written clients) */
453     GNUNET_NETWORK_fdset_copy (want, ready);
454     return GNUNET_YES;
455   }
456   return GNUNET_NO;
457 }
458
459
460 /**
461  * Check if the given task is eligible to run now.
462  * Also set the reason why it is eligible.
463  *
464  * @param task task to check if it is ready
465  * @param now the current time
466  * @param rs set of FDs ready for reading
467  * @param ws set of FDs ready for writing
468  * @return #GNUNET_YES if we can run it, #GNUNET_NO if not.
469  */
470 static int
471 is_ready (struct GNUNET_SCHEDULER_Task *task,
472           struct GNUNET_TIME_Absolute now,
473           const struct GNUNET_NETWORK_FDSet *rs,
474           const struct GNUNET_NETWORK_FDSet *ws)
475 {
476   enum GNUNET_SCHEDULER_Reason reason;
477
478   reason = task->reason;
479   if (now.abs_value_us >= task->timeout.abs_value_us)
480     reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
481   if ((0 == (reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
482       (((task->read_fd != -1) &&
483         (GNUNET_YES == GNUNET_NETWORK_fdset_test_native (rs, task->read_fd))) ||
484        (set_overlaps (rs, task->read_set))))
485     reason |= GNUNET_SCHEDULER_REASON_READ_READY;
486   if ((0 == (reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) &&
487       (((task->write_fd != -1) &&
488         (GNUNET_YES == GNUNET_NETWORK_fdset_test_native (ws, task->write_fd)))
489        || (set_overlaps (ws, task->write_set))))
490     reason |= GNUNET_SCHEDULER_REASON_WRITE_READY;
491   if (0 == reason)
492     return GNUNET_NO;           /* not ready */
493   reason |= GNUNET_SCHEDULER_REASON_PREREQ_DONE;
494   task->reason = reason;
495   return GNUNET_YES;
496 }
497
498
499 /**
500  * Put a task that is ready for execution into the ready queue.
501  *
502  * @param task task ready for execution
503  */
504 static void
505 queue_ready_task (struct GNUNET_SCHEDULER_Task *task)
506 {
507   enum GNUNET_SCHEDULER_Priority p = check_priority (task->priority);
508
509   GNUNET_CONTAINER_DLL_insert (ready_head[p],
510                                ready_tail[p],
511                                task);
512   task->in_ready_list = GNUNET_YES;
513   ready_count++;
514 }
515
516
517 /**
518  * Check which tasks are ready and move them
519  * to the respective ready queue.
520  *
521  * @param rs FDs ready for reading
522  * @param ws FDs ready for writing
523  */
524 static void
525 check_ready (const struct GNUNET_NETWORK_FDSet *rs,
526              const struct GNUNET_NETWORK_FDSet *ws)
527 {
528   struct GNUNET_SCHEDULER_Task *pos;
529   struct GNUNET_SCHEDULER_Task *next;
530   struct GNUNET_TIME_Absolute now;
531
532   now = GNUNET_TIME_absolute_get ();
533   while (NULL != (pos = pending_timeout_head))
534   {
535     if (now.abs_value_us >= pos->timeout.abs_value_us)
536       pos->reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
537     if (0 == pos->reason)
538       break;
539     GNUNET_CONTAINER_DLL_remove (pending_timeout_head,
540                                  pending_timeout_tail,
541                                  pos);
542     scheduler_driver->set_wakeup(scheduler_driver->cls,pending_timeout_head->timeout);
543     if (pending_timeout_last == pos)
544       pending_timeout_last = NULL;
545     queue_ready_task (pos);
546   }
547   pos = pending_head;
548   while (NULL != pos)
549   {
550     next = pos->next;
551     if (GNUNET_YES == is_ready (pos, now, rs, ws))
552     {
553       GNUNET_CONTAINER_DLL_remove (pending_head,
554                                    pending_tail,
555                                    pos);
556       queue_ready_task (pos);
557     }
558     pos = next;
559   }
560 }
561
562
563 /**
564  * Request the shutdown of a scheduler.  Marks all tasks
565  * awaiting shutdown as ready. Note that tasks
566  * scheduled with #GNUNET_SCHEDULER_add_shutdown() AFTER this call
567  * will be delayed until the next shutdown signal.
568  */
569 void
570 GNUNET_SCHEDULER_shutdown ()
571 {
572   struct GNUNET_SCHEDULER_Task *pos;
573
574   while (NULL != (pos = shutdown_head))
575   {
576     GNUNET_CONTAINER_DLL_remove (shutdown_head,
577                                  shutdown_tail,
578                                  pos);
579     pos->reason |= GNUNET_SCHEDULER_REASON_SHUTDOWN;
580     queue_ready_task (pos);
581   }
582 }
583
584
585 /**
586  * Destroy a task (release associated resources)
587  *
588  * @param t task to destroy
589  */
590 static void
591 destroy_task (struct GNUNET_SCHEDULER_Task *t)
592 {
593   if (NULL != t->read_set)
594     GNUNET_NETWORK_fdset_destroy (t->read_set);
595   if (NULL != t->write_set)
596     GNUNET_NETWORK_fdset_destroy (t->write_set);
597 #if EXECINFO
598   GNUNET_free (t->backtrace_strings);
599 #endif
600   GNUNET_free (t);
601 }
602
603
604 /**
605  * Output stack trace of task @a t.
606  *
607  * @param t task to dump stack trace of
608  */
609 static void
610 dump_backtrace (struct GNUNET_SCHEDULER_Task *t)
611 {
612 #if EXECINFO
613   unsigned int i;
614
615   for (i = 0; i < t->num_backtrace_strings; i++)
616     LOG (GNUNET_ERROR_TYPE_DEBUG,
617    "Task %p trace %u: %s\n",
618    t,
619    i,
620    t->backtrace_strings[i]);
621 #endif
622 }
623
624
625 /**
626  * Run at least one task in the highest-priority queue that is not
627  * empty.  Keep running tasks until we are either no longer running
628  * "URGENT" tasks or until we have at least one "pending" task (which
629  * may become ready, hence we should select on it).  Naturally, if
630  * there are no more ready tasks, we also return.
631  *
632  * @param rs FDs ready for reading
633  * @param ws FDs ready for writing
634  */
635 static void
636 run_ready (struct GNUNET_NETWORK_FDSet *rs,
637            struct GNUNET_NETWORK_FDSet *ws)
638 {
639   enum GNUNET_SCHEDULER_Priority p;
640   struct GNUNET_SCHEDULER_Task *pos;
641
642   max_priority_added = GNUNET_SCHEDULER_PRIORITY_KEEP;
643   do
644   {
645     if (0 == ready_count)
646       return;
647     GNUNET_assert (NULL == ready_head[GNUNET_SCHEDULER_PRIORITY_KEEP]);
648     /* yes, p>0 is correct, 0 is "KEEP" which should
649      * always be an empty queue (see assertion)! */
650     for (p = GNUNET_SCHEDULER_PRIORITY_COUNT - 1; p > 0; p--)
651     {
652       pos = ready_head[p];
653       if (NULL != pos)
654         break;
655     }
656     GNUNET_assert (NULL != pos);        /* ready_count wrong? */
657     GNUNET_CONTAINER_DLL_remove (ready_head[p],
658                                  ready_tail[p],
659                                  pos);
660     ready_count--;
661     current_priority = pos->priority;
662     current_lifeness = pos->lifeness;
663     active_task = pos;
664 #if PROFILE_DELAYS
665     if (GNUNET_TIME_absolute_get_duration (pos->start_time).rel_value_us >
666         DELAY_THRESHOLD.rel_value_us)
667     {
668       LOG (GNUNET_ERROR_TYPE_DEBUG,
669      "Task %p took %s to be scheduled\n",
670            pos,
671            GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pos->start_time),
672                                                    GNUNET_YES));
673     }
674 #endif
675     tc.reason = pos->reason;
676     tc.read_ready = (NULL == pos->read_set) ? rs : pos->read_set;
677     if ((-1 != pos->read_fd) &&
678         (0 != (pos->reason & GNUNET_SCHEDULER_REASON_READ_READY)))
679       GNUNET_NETWORK_fdset_set_native (rs, pos->read_fd);
680     tc.write_ready = (NULL == pos->write_set) ? ws : pos->write_set;
681     if ((-1 != pos->write_fd) &&
682         (0 != (pos->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)))
683       GNUNET_NETWORK_fdset_set_native (ws, pos->write_fd);
684     if ((0 != (tc.reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) &&
685         (-1 != pos->write_fd) &&
686         (!GNUNET_NETWORK_fdset_test_native (ws, pos->write_fd)))
687       GNUNET_assert (0);          // added to ready in previous select loop!
688     LOG (GNUNET_ERROR_TYPE_DEBUG,
689    "Running task: %p\n",
690          pos);
691     pos->callback (pos->callback_cls);
692     dump_backtrace (pos);
693     active_task = NULL;
694     destroy_task (pos);
695     tasks_run++;
696   }
697   while ((NULL == pending_head) || (p >= max_priority_added));
698 }
699
700
701 /**
702  * Pipe used to communicate shutdown via signal.
703  */
704 static struct GNUNET_DISK_PipeHandle *shutdown_pipe_handle;
705
706 /**
707  * Process ID of this process at the time we installed the various
708  * signal handlers.
709  */
710 static pid_t my_pid;
711
712 /**
713  * Signal handler called for SIGPIPE.
714  */
715 #ifndef MINGW
716 static void
717 sighandler_pipe ()
718 {
719   return;
720 }
721 #endif
722
723
724 /**
725  * Wait for a short time.
726  * Sleeps for @a ms ms (as that should be long enough for virtually all
727  * modern systems to context switch and allow another process to do
728  * some 'real' work).
729  *
730  * @param ms how many ms to wait
731  */
732 static void
733 short_wait (unsigned int ms)
734 {
735   struct GNUNET_TIME_Relative timeout;
736
737   timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, ms);
738   (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout);
739 }
740
741
742 /**
743  * Signal handler called for signals that should cause us to shutdown.
744  */
745 static void
746 sighandler_shutdown ()
747 {
748   static char c;
749   int old_errno = errno;        /* backup errno */
750
751   if (getpid () != my_pid)
752     exit (1);                   /* we have fork'ed since the signal handler was created,
753                                  * ignore the signal, see https://gnunet.org/vfork discussion */
754   GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
755                           (shutdown_pipe_handle, GNUNET_DISK_PIPE_END_WRITE),
756                           &c, sizeof (c));
757   errno = old_errno;
758 }
759
760
761 /**
762  * Check if the system is still alive. Trigger shutdown if we
763  * have tasks, but none of them give us lifeness.
764  *
765  * @return #GNUNET_OK to continue the main loop,
766  *         #GNUNET_NO to exit
767  */
768 static int
769 check_lifeness ()
770 {
771   struct GNUNET_SCHEDULER_Task *t;
772
773   if (ready_count > 0)
774     return GNUNET_OK;
775   for (t = pending_head; NULL != t; t = t->next)
776     if (t->lifeness == GNUNET_YES)
777       return GNUNET_OK;
778   for (t = shutdown_head; NULL != t; t = t->next)
779     if (t->lifeness == GNUNET_YES)
780       return GNUNET_OK;
781   for (t = pending_timeout_head; NULL != t; t = t->next)
782     if (t->lifeness == GNUNET_YES)
783       return GNUNET_OK;
784   if (NULL != shutdown_head)
785   {
786     GNUNET_SCHEDULER_shutdown ();
787     return GNUNET_OK;
788   }
789   return GNUNET_NO;
790 }
791
792
793
794 void while_live(struct GNUNET_NETWORK_FDSet *rs, struct GNUNET_NETWORK_FDSet *ws)
795 {
796   int ret;
797   unsigned int busy_wait_warning;
798   unsigned long long last_tr;
799   const struct GNUNET_DISK_FileHandle *pr;
800   char c;
801   struct GNUNET_TIME_Relative timeout;
802
803   busy_wait_warning = 0;
804   pr = GNUNET_DISK_pipe_handle (shutdown_pipe_handle,
805                                 GNUNET_DISK_PIPE_END_READ);
806   GNUNET_assert (NULL != pr);
807   last_tr = 0;
808
809   while (GNUNET_OK == check_lifeness ())
810   {
811     GNUNET_NETWORK_fdset_zero (rs);
812     GNUNET_NETWORK_fdset_zero (ws);
813     timeout = GNUNET_TIME_UNIT_FOREVER_REL;
814     update_sets (rs, ws, &timeout);
815     GNUNET_NETWORK_fdset_handle_set (rs, pr);
816     if (ready_count > 0)
817     {
818       /* no blocking, more work already ready! */
819       timeout = GNUNET_TIME_UNIT_ZERO;
820     }
821     if (NULL == scheduler_select)
822       ret = GNUNET_NETWORK_socket_select (rs,
823                                           ws,
824                                           NULL,
825                                           timeout);
826     else
827       ret = scheduler_select (scheduler_select_cls,
828                               rs,
829                               ws,
830                               NULL,
831                               timeout);
832     if (ret == GNUNET_SYSERR)
833     {
834       if (errno == EINTR)
835         continue;
836
837       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "select");
838 #ifndef MINGW
839 #if USE_LSOF
840       char lsof[512];
841
842       snprintf (lsof, sizeof (lsof), "lsof -p %d", getpid ());
843       (void) close (1);
844       (void) dup2 (2, 1);
845       if (0 != system (lsof))
846         LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING,
847                       "system");
848 #endif
849 #endif
850 #if DEBUG_FDS
851       struct GNUNET_SCHEDULER_Task *t;
852
853       for (t = pending_head; NULL != t; t = t->next)
854       {
855         if (-1 != t->read_fd)
856         {
857           int flags = fcntl (t->read_fd, F_GETFD);
858           if ((flags == -1) && (errno == EBADF))
859             {
860               LOG (GNUNET_ERROR_TYPE_ERROR,
861                    "Got invalid file descriptor %d!\n",
862                    t->read_fd);
863               dump_backtrace (t);
864             }
865         }
866         if (-1 != t->write_fd)
867           {
868             int flags = fcntl (t->write_fd, F_GETFD);
869             if ((flags == -1) && (errno == EBADF))
870               {
871                 LOG (GNUNET_ERROR_TYPE_ERROR,
872                      "Got invalid file descriptor %d!\n",
873                      t->write_fd);
874                 dump_backtrace (t);
875               }
876           }
877       }
878 #endif
879       GNUNET_assert (0);
880       break;
881     }
882
883     if ( (0 == ret) &&
884          (0 == timeout.rel_value_us) &&
885          (busy_wait_warning > 16) )
886     {
887       LOG (GNUNET_ERROR_TYPE_WARNING,
888            "Looks like we're busy waiting...\n");
889       short_wait (100);                /* mitigate */
890     }
891     check_ready (rs, ws);
892     run_ready (rs, ws);
893     if (GNUNET_NETWORK_fdset_handle_isset (rs, pr))
894     {
895       /* consume the signal */
896       GNUNET_DISK_file_read (pr, &c, sizeof (c));
897       /* mark all active tasks as ready due to shutdown */
898       GNUNET_SCHEDULER_shutdown ();
899     }
900     if (last_tr == tasks_run)
901     {
902       short_wait (1);
903       busy_wait_warning++;
904     }
905     else
906     {
907       last_tr = tasks_run;
908       busy_wait_warning = 0;
909     }
910   }
911 }
912
913 /**
914  * Initialize and run scheduler.  This function will return when all
915  * tasks have completed.  On systems with signals, receiving a SIGTERM
916  * (and other similar signals) will cause #GNUNET_SCHEDULER_shutdown()
917  * to be run after the active task is complete.  As a result, SIGTERM
918  * causes all active tasks to be scheduled with reason
919  * #GNUNET_SCHEDULER_REASON_SHUTDOWN.  (However, tasks added
920  * afterwards will execute normally!). Note that any particular signal
921  * will only shut down one scheduler; applications should always only
922  * create a single scheduler.
923  *
924  * @param task task to run immediately
925  * @param task_cls closure of @a task
926  */
927 void
928 GNUNET_SCHEDULER_run (GNUNET_SCHEDULER_TaskCallback task,
929                       void *task_cls)
930 {
931   struct GNUNET_NETWORK_FDSet *rs;
932   struct GNUNET_NETWORK_FDSet *ws;
933
934
935   struct GNUNET_SIGNAL_Context *shc_int;
936   struct GNUNET_SIGNAL_Context *shc_term;
937 #if (SIGTERM != GNUNET_TERM_SIG)
938   struct GNUNET_SIGNAL_Context *shc_gterm;
939 #endif
940
941 #ifndef MINGW
942   struct GNUNET_SIGNAL_Context *shc_quit;
943   struct GNUNET_SIGNAL_Context *shc_hup;
944   struct GNUNET_SIGNAL_Context *shc_pipe;
945 #endif
946
947
948
949   GNUNET_assert (NULL == active_task);
950   rs = GNUNET_NETWORK_fdset_create ();
951   ws = GNUNET_NETWORK_fdset_create ();
952   GNUNET_assert (NULL == shutdown_pipe_handle);
953   shutdown_pipe_handle = GNUNET_DISK_pipe (GNUNET_NO,
954                                            GNUNET_NO,
955                                            GNUNET_NO,
956                                            GNUNET_NO);
957   GNUNET_assert (NULL != shutdown_pipe_handle);
958
959   my_pid = getpid ();
960   LOG (GNUNET_ERROR_TYPE_DEBUG,
961        "Registering signal handlers\n");
962   shc_int = GNUNET_SIGNAL_handler_install (SIGINT,
963              &sighandler_shutdown);
964   shc_term = GNUNET_SIGNAL_handler_install (SIGTERM,
965               &sighandler_shutdown);
966 #if (SIGTERM != GNUNET_TERM_SIG)
967   shc_gterm = GNUNET_SIGNAL_handler_install (GNUNET_TERM_SIG,
968                &sighandler_shutdown);
969 #endif
970 #ifndef MINGW
971   shc_pipe = GNUNET_SIGNAL_handler_install (SIGPIPE,
972               &sighandler_pipe);
973   shc_quit = GNUNET_SIGNAL_handler_install (SIGQUIT,
974               &sighandler_shutdown);
975   shc_hup = GNUNET_SIGNAL_handler_install (SIGHUP,
976              &sighandler_shutdown);
977 #endif
978   current_priority = GNUNET_SCHEDULER_PRIORITY_DEFAULT;
979   current_lifeness = GNUNET_YES;
980   GNUNET_SCHEDULER_add_with_reason_and_priority (task,
981                                                  task_cls,
982                                                  GNUNET_SCHEDULER_REASON_STARTUP,
983                                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT);
984   active_task = (void *) (long) -1;     /* force passing of sanity check */
985   GNUNET_SCHEDULER_add_now_with_lifeness (GNUNET_NO,
986                                           &GNUNET_OS_install_parent_control_handler,
987                                           NULL);
988   active_task = NULL;
989
990
991   while_live(rs, ws);
992   GNUNET_SIGNAL_handler_uninstall (shc_int);
993   GNUNET_SIGNAL_handler_uninstall (shc_term);
994 #if (SIGTERM != GNUNET_TERM_SIG)
995   GNUNET_SIGNAL_handler_uninstall (shc_gterm);
996 #endif
997 #ifndef MINGW
998   GNUNET_SIGNAL_handler_uninstall (shc_pipe);
999   GNUNET_SIGNAL_handler_uninstall (shc_quit);
1000   GNUNET_SIGNAL_handler_uninstall (shc_hup);
1001 #endif
1002   GNUNET_DISK_pipe_close (shutdown_pipe_handle);
1003   shutdown_pipe_handle = NULL;
1004   GNUNET_NETWORK_fdset_destroy (rs);
1005   GNUNET_NETWORK_fdset_destroy (ws);
1006 }
1007
1008
1009 /**
1010  * Obtain the task context, giving the reason why the current task was
1011  * started.
1012  *
1013  * @return current tasks' scheduler context
1014  */
1015 const struct GNUNET_SCHEDULER_TaskContext *
1016 GNUNET_SCHEDULER_get_task_context ()
1017 {
1018   GNUNET_assert (NULL != active_task);
1019   return &tc;
1020 }
1021
1022
1023 /**
1024  * Get information about the current load of this scheduler.  Use this
1025  * function to determine if an elective task should be added or simply
1026  * dropped (if the decision should be made based on the number of
1027  * tasks ready to run).
1028  *
1029  * @param p priority level to look at
1030  * @return number of tasks pending right now
1031  */
1032 unsigned int
1033 GNUNET_SCHEDULER_get_load (enum GNUNET_SCHEDULER_Priority p)
1034 {
1035   struct GNUNET_SCHEDULER_Task *pos;
1036   unsigned int ret;
1037
1038   GNUNET_assert (NULL != active_task);
1039   if (p == GNUNET_SCHEDULER_PRIORITY_COUNT)
1040     return ready_count;
1041   if (p == GNUNET_SCHEDULER_PRIORITY_KEEP)
1042     p = current_priority;
1043   ret = 0;
1044   for (pos = ready_head[check_priority (p)]; NULL != pos; pos = pos->next)
1045     ret++;
1046   return ret;
1047 }
1048
1049 static struct GNUNET_SCHEDULER_Task*
1050 initFdInfo(const struct GNUNET_NETWORK_Handle *read_nh,
1051            const struct GNUNET_NETWORK_Handle *write_nh,
1052            const struct GNUNET_DISK_FileHandle *read_fh,
1053            const struct GNUNET_DISK_FileHandle *write_fh)
1054 {
1055
1056
1057   struct GNUNET_SCHEDULER_Task *t;
1058
1059   t = GNUNET_new (struct GNUNET_SCHEDULER_Task);
1060
1061   // either only network handles or only file handles are allowed
1062   GNUNET_assert (!((NULL != read_nh || NULL != write_nh) && (NULL != read_fh || NULL != write_fh)));
1063
1064   if (NULL != read_nh && NULL != write_nh)
1065   {
1066     t->fds_len = 2;
1067     t->fds = GNUNET_new_array (2, struct GNUNET_SCHEDULER_FdInfo);
1068     const struct GNUNET_SCHEDULER_FdInfo read_fdi = { .fd = read_nh, .et = GNUNET_SCHEDULER_ET_IN, .sock = GNUNET_NETWORK_get_fd (read_nh)};
1069     const struct GNUNET_SCHEDULER_FdInfo write_fdi = { .fd = write_nh, .et = GNUNET_SCHEDULER_ET_OUT, .sock = GNUNET_NETWORK_get_fd (write_nh)};
1070
1071     const struct GNUNET_SCHEDULER_FdInfo array[2] = {read_fdi, write_fdi};
1072     t->fds = array;
1073   }
1074   else if (NULL != read_fh && NULL != write_fh)
1075   {
1076     t->fds_len = 2;
1077     t->fds = GNUNET_new_array (2, struct GNUNET_SCHEDULER_FdInfo);
1078     const struct GNUNET_SCHEDULER_FdInfo read_fdi = { .fh = read_fh, .et = GNUNET_SCHEDULER_ET_IN};
1079     const struct GNUNET_SCHEDULER_FdInfo write_fdi = { .fh = write_fh, .et = GNUNET_SCHEDULER_ET_OUT, .sock = GNUNET_NETWORK_get_fd (write_nh)};
1080     const struct GNUNET_SCHEDULER_FdInfo array[2] = {read_fdi, write_fdi};
1081     t->fds = array;
1082   }
1083   else if (NULL != read_nh)
1084   {
1085     struct GNUNET_SCHEDULER_FdInfo read_fdi = { .fd = read_nh, .et = GNUNET_SCHEDULER_ET_IN, .sock = GNUNET_NETWORK_get_fd (read_nh)};
1086     t->fdx = read_fdi;
1087   }
1088   else if (NULL != write_nh)
1089   {
1090     struct GNUNET_SCHEDULER_FdInfo write_fdi = { .fd = write_nh, .et = GNUNET_SCHEDULER_ET_OUT, .sock = GNUNET_NETWORK_get_fd (write_nh)};
1091     t->fdx = write_fdi;
1092   }
1093   else if (NULL != read_fh)
1094   {
1095     struct GNUNET_SCHEDULER_FdInfo read_fdi = { .fh = read_fh, .et = GNUNET_SCHEDULER_ET_IN};
1096     t->fdx = read_fdi;
1097   }
1098   else if (NULL != write_fh)
1099   {
1100     struct GNUNET_SCHEDULER_FdInfo write_fdi = { .fh = write_fh, .et = GNUNET_SCHEDULER_ET_OUT, .sock = GNUNET_NETWORK_get_fd (write_nh)};
1101     t->fdx = write_fdi;
1102   }
1103 }
1104
1105 /**
1106  * Cancel the task with the specified identifier.
1107  * The task must not yet have run.
1108  *
1109  * @param task id of the task to cancel
1110  * @return original closure of the task
1111  */
1112 void *
1113 GNUNET_SCHEDULER_cancel (struct GNUNET_SCHEDULER_Task *task)
1114 {
1115   enum GNUNET_SCHEDULER_Priority p;
1116   void *ret;
1117
1118   GNUNET_assert ( (NULL != active_task) ||
1119       (GNUNET_NO == task->lifeness) );
1120   if (! task->in_ready_list)
1121   {
1122     if ( (-1 == task->read_fd) &&
1123          (-1 == task->write_fd) &&
1124          (NULL == task->read_set) &&
1125          (NULL == task->write_set) )
1126     {
1127       if (GNUNET_YES == task->on_shutdown)
1128   GNUNET_CONTAINER_DLL_remove (shutdown_head,
1129              shutdown_tail,
1130              task);
1131       else
1132   GNUNET_CONTAINER_DLL_remove (pending_timeout_head,
1133              pending_timeout_tail,
1134              task);
1135       scheduler_driver->set_wakeup(scheduler_driver->cls,pending_timeout_head->timeout);
1136       if (task == pending_timeout_last)
1137         pending_timeout_last = NULL;
1138     }
1139     else
1140     {
1141       scheduler_multi_function_call(task, scheduler_driver->del);
1142     }
1143   }
1144   else
1145   {
1146     p = check_priority (task->priority);
1147     GNUNET_CONTAINER_DLL_remove (ready_head[p],
1148                                  ready_tail[p],
1149                                  task);
1150     ready_count--;
1151   }
1152   ret = task->callback_cls;
1153   LOG (GNUNET_ERROR_TYPE_DEBUG,
1154        "Canceling task %p\n",
1155        task);
1156   destroy_task (task);
1157   return ret;
1158 }
1159
1160
1161 /**
1162  * Initialize backtrace data for task @a t
1163  *
1164  * @param t task to initialize
1165  */
1166 static void
1167 init_backtrace (struct GNUNET_SCHEDULER_Task *t)
1168 {
1169 #if EXECINFO
1170   void *backtrace_array[MAX_TRACE_DEPTH];
1171
1172   t->num_backtrace_strings
1173     = backtrace (backtrace_array, MAX_TRACE_DEPTH);
1174   t->backtrace_strings =
1175       backtrace_symbols (backtrace_array,
1176        t->num_backtrace_strings);
1177   dump_backtrace (t);
1178 #endif
1179 }
1180
1181
1182 /**
1183  * Continue the current execution with the given function.  This is
1184  * similar to the other "add" functions except that there is no delay
1185  * and the reason code can be specified.
1186  *
1187  * @param task main function of the task
1188  * @param task_cls closure for @a task
1189  * @param reason reason for task invocation
1190  * @param priority priority to use for the task
1191  */
1192 void
1193 GNUNET_SCHEDULER_add_with_reason_and_priority (GNUNET_SCHEDULER_TaskCallback task,
1194                                                void *task_cls,
1195                                                enum GNUNET_SCHEDULER_Reason reason,
1196                                                enum GNUNET_SCHEDULER_Priority priority)
1197 {
1198   struct GNUNET_SCHEDULER_Task *t;
1199
1200   GNUNET_assert (NULL != task);
1201   GNUNET_assert ((NULL != active_task) ||
1202                  (GNUNET_SCHEDULER_REASON_STARTUP == reason));
1203   t = GNUNET_new (struct GNUNET_SCHEDULER_Task);
1204   t->read_fd = -1;
1205   t->write_fd = -1;
1206   t->callback = task;
1207   t->callback_cls = task_cls;
1208 #if PROFILE_DELAYS
1209   t->start_time = GNUNET_TIME_absolute_get ();
1210 #endif
1211   t->reason = reason;
1212   t->priority = priority;
1213   t->lifeness = current_lifeness;
1214   LOG (GNUNET_ERROR_TYPE_DEBUG,
1215        "Adding continuation task %p\n",
1216        t);
1217   init_backtrace (t);
1218   queue_ready_task (t);
1219 }
1220
1221
1222 /**
1223  * Schedule a new task to be run at the specified time.  The task
1224  * will be scheduled for execution at time @a at.
1225  *
1226  * @param at time when the operation should run
1227  * @param priority priority to use for the task
1228  * @param task main function of the task
1229  * @param task_cls closure of @a task
1230  * @return unique task identifier for the job
1231  *         only valid until @a task is started!
1232  */
1233 struct GNUNET_SCHEDULER_Task *
1234 GNUNET_SCHEDULER_add_at_with_priority (struct GNUNET_TIME_Absolute at,
1235                                        enum GNUNET_SCHEDULER_Priority priority,
1236                                        GNUNET_SCHEDULER_TaskCallback task,
1237                                        void *task_cls)
1238 {
1239   struct GNUNET_SCHEDULER_Task *t;
1240   struct GNUNET_SCHEDULER_Task *pos;
1241   struct GNUNET_SCHEDULER_Task *prev;
1242
1243   GNUNET_assert (NULL != active_task);
1244   GNUNET_assert (NULL != task);
1245   t = GNUNET_new (struct GNUNET_SCHEDULER_Task);
1246   t->callback = task;
1247   t->callback_cls = task_cls;
1248   t->read_fd = -1;
1249   t->write_fd = -1;
1250 #if PROFILE_DELAYS
1251   t->start_time = GNUNET_TIME_absolute_get ();
1252 #endif
1253   t->timeout = at;
1254   t->priority = priority;
1255   t->lifeness = current_lifeness;
1256   /* try tail first (optimization in case we are
1257    * appending to a long list of tasks with timeouts) */
1258   if ( (NULL == pending_timeout_head) ||
1259        (at.abs_value_us < pending_timeout_head->timeout.abs_value_us) )
1260   {
1261     GNUNET_CONTAINER_DLL_insert (pending_timeout_head,
1262                                  pending_timeout_tail,
1263                                  t);
1264     scheduler_driver->set_wakeup(scheduler_driver->cls,pending_timeout_head->timeout);
1265   }
1266   else
1267   {
1268     /* first move from heuristic start backwards to before start time */
1269     prev = pending_timeout_last;
1270     while ( (NULL != prev) &&
1271             (prev->timeout.abs_value_us > t->timeout.abs_value_us) )
1272       prev = prev->prev;
1273     /* now, move from heuristic start (or head of list) forward to insertion point */
1274     if (NULL == prev)
1275       pos = pending_timeout_head;
1276     else
1277       pos = prev->next;
1278     while ( (NULL != pos) &&
1279             ( (pos->timeout.abs_value_us <= t->timeout.abs_value_us) ||
1280               (0 != pos->reason) ) )
1281     {
1282       prev = pos;
1283       pos = pos->next;
1284     }
1285     GNUNET_CONTAINER_DLL_insert_after (pending_timeout_head,
1286                                        pending_timeout_tail,
1287                                        prev,
1288                                        t);
1289   }
1290   /* finally, update heuristic insertion point to last insertion... */
1291   pending_timeout_last = t;
1292
1293   LOG (GNUNET_ERROR_TYPE_DEBUG,
1294        "Adding task: %p\n",
1295        t);
1296   init_backtrace (t);
1297   return t;
1298 }
1299
1300
1301 /**
1302  * Schedule a new task to be run with a specified delay.  The task
1303  * will be scheduled for execution once the delay has expired.
1304  *
1305  * @param delay when should this operation time out?
1306  * @param priority priority to use for the task
1307  * @param task main function of the task
1308  * @param task_cls closure of @a task
1309  * @return unique task identifier for the job
1310  *         only valid until @a task is started!
1311  */
1312 struct GNUNET_SCHEDULER_Task *
1313 GNUNET_SCHEDULER_add_delayed_with_priority (struct GNUNET_TIME_Relative delay,
1314               enum GNUNET_SCHEDULER_Priority priority,
1315               GNUNET_SCHEDULER_TaskCallback task,
1316                                             void *task_cls)
1317 {
1318   return GNUNET_SCHEDULER_add_at_with_priority (GNUNET_TIME_relative_to_absolute (delay),
1319                                                 priority,
1320                                                 task,
1321                                                 task_cls);
1322 }
1323
1324
1325 /**
1326  * Schedule a new task to be run with a specified priority.
1327  *
1328  * @param prio how important is the new task?
1329  * @param task main function of the task
1330  * @param task_cls closure of @a task
1331  * @return unique task identifier for the job
1332  *         only valid until @a task is started!
1333  */
1334 struct GNUNET_SCHEDULER_Task *
1335 GNUNET_SCHEDULER_add_with_priority (enum GNUNET_SCHEDULER_Priority prio,
1336                                     GNUNET_SCHEDULER_TaskCallback task,
1337                                     void *task_cls)
1338 {
1339   return GNUNET_SCHEDULER_add_delayed_with_priority (GNUNET_TIME_UNIT_ZERO,
1340                                                      prio,
1341                                                      task,
1342                                                      task_cls);
1343 }
1344
1345
1346 /**
1347  * Schedule a new task to be run at the specified time.  The task
1348  * will be scheduled for execution once specified time has been
1349  * reached. It will be run with the DEFAULT priority.
1350  *
1351  * @param at time at which this operation should run
1352  * @param task main function of the task
1353  * @param task_cls closure of @a task
1354  * @return unique task identifier for the job
1355  *         only valid until @a task is started!
1356  */
1357 struct GNUNET_SCHEDULER_Task *
1358 GNUNET_SCHEDULER_add_at (struct GNUNET_TIME_Absolute at,
1359                          GNUNET_SCHEDULER_TaskCallback task,
1360                          void *task_cls)
1361 {
1362   return GNUNET_SCHEDULER_add_at_with_priority (at,
1363                                                 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1364                                                 task,
1365                                                 task_cls);
1366 }
1367
1368
1369 /**
1370  * Schedule a new task to be run with a specified delay.  The task
1371  * will be scheduled for execution once the delay has expired. It
1372  * will be run with the DEFAULT priority.
1373  *
1374  * @param delay when should this operation time out?
1375  * @param task main function of the task
1376  * @param task_cls closure of @a task
1377  * @return unique task identifier for the job
1378  *         only valid until @a task is started!
1379  */
1380 struct GNUNET_SCHEDULER_Task *
1381 GNUNET_SCHEDULER_add_delayed (struct GNUNET_TIME_Relative delay,
1382                               GNUNET_SCHEDULER_TaskCallback task,
1383             void *task_cls)
1384 {
1385   return GNUNET_SCHEDULER_add_delayed_with_priority (delay,
1386                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1387                  task,
1388                                                      task_cls);
1389 }
1390
1391
1392 /**
1393  * Schedule a new task to be run as soon as possible.  Note that this
1394  * does not guarantee that this will be the next task that is being
1395  * run, as other tasks with higher priority (or that are already ready
1396  * to run) might get to run first.  Just as with delays, clients must
1397  * not rely on any particular order of execution between tasks
1398  * scheduled concurrently.
1399  *
1400  * The task will be run with the DEFAULT priority.
1401  *
1402  * @param task main function of the task
1403  * @param task_cls closure of @a task
1404  * @return unique task identifier for the job
1405  *         only valid until @a task is started!
1406  */
1407 struct GNUNET_SCHEDULER_Task *
1408 GNUNET_SCHEDULER_add_now (GNUNET_SCHEDULER_TaskCallback task,
1409         void *task_cls)
1410 {
1411   return GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_ZERO,
1412                task,
1413                task_cls);
1414 }
1415
1416
1417 /**
1418  * Schedule a new task to be run on shutdown, that is when a CTRL-C
1419  * signal is received, or when #GNUNET_SCHEDULER_shutdown() is being
1420  * invoked.
1421  *
1422  * @param task main function of the task
1423  * @param task_cls closure of @a task
1424  * @return unique task identifier for the job
1425  *         only valid until @a task is started!
1426  */
1427 struct GNUNET_SCHEDULER_Task *
1428 GNUNET_SCHEDULER_add_shutdown (GNUNET_SCHEDULER_TaskCallback task,
1429              void *task_cls)
1430 {
1431   struct GNUNET_SCHEDULER_Task *t;
1432
1433   GNUNET_assert (NULL != active_task);
1434   GNUNET_assert (NULL != task);
1435   t = GNUNET_new (struct GNUNET_SCHEDULER_Task);
1436   t->callback = task;
1437   t->callback_cls = task_cls;
1438   t->read_fd = -1;
1439   t->write_fd = -1;
1440 #if PROFILE_DELAYS
1441   t->start_time = GNUNET_TIME_absolute_get ();
1442 #endif
1443   t->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1444   t->priority = GNUNET_SCHEDULER_PRIORITY_SHUTDOWN;
1445   t->on_shutdown = GNUNET_YES;
1446   t->lifeness = GNUNET_YES;
1447   GNUNET_CONTAINER_DLL_insert (shutdown_head,
1448              shutdown_tail,
1449              t);
1450   LOG (GNUNET_ERROR_TYPE_DEBUG,
1451        "Adding task: %p\n",
1452        t);
1453   init_backtrace (t);
1454   return t;
1455 }
1456
1457
1458 /**
1459  * Schedule a new task to be run as soon as possible with the
1460  * (transitive) ignore-shutdown flag either explicitly set or
1461  * explicitly enabled.  This task (and all tasks created from it,
1462  * other than by another call to this function) will either count or
1463  * not count for the "lifeness" of the process.  This API is only
1464  * useful in a few special cases.
1465  *
1466  * @param lifeness #GNUNET_YES if the task counts for lifeness, #GNUNET_NO if not.
1467  * @param task main function of the task
1468  * @param task_cls closure of @a task
1469  * @return unique task identifier for the job
1470  *         only valid until @a task is started!
1471  */
1472 struct GNUNET_SCHEDULER_Task *
1473 GNUNET_SCHEDULER_add_now_with_lifeness (int lifeness,
1474                                         GNUNET_SCHEDULER_TaskCallback task,
1475                                         void *task_cls)
1476 {
1477   struct GNUNET_SCHEDULER_Task *ret;
1478
1479   ret = GNUNET_SCHEDULER_add_now (task, task_cls);
1480   ret->lifeness = lifeness;
1481   return ret;
1482 }
1483
1484
1485
1486 int scheduler_multi_function_call(struct GNUNET_SCHEDULER_Task *t, int (*driver_func)())
1487 {
1488   if (t->fds_len > 1){
1489     int success = GNUNET_YES;
1490     for (int i = 0; i < t->fds_len;i++){
1491       success = driver_func(scheduler_driver->cls, t , t->fds+i) && success;
1492     }
1493     return success;
1494   }else{
1495     return driver_func(scheduler_driver->cls, t , t->fds);
1496   }
1497 }
1498
1499 /**
1500  * Schedule a new task to be run with a specified delay or when any of
1501  * the specified file descriptor sets is ready.  The delay can be used
1502  * as a timeout on the socket(s) being ready.  The task will be
1503  * scheduled for execution once either the delay has expired or any of
1504  * the socket operations is ready.  This is the most general
1505  * function of the "add" family.  Note that the "prerequisite_task"
1506  * must be satisfied in addition to any of the other conditions.  In
1507  * other words, the task will be started when
1508  * <code>
1509  * (prerequisite-run)
1510  * && (delay-ready
1511  *     || any-rs-ready
1512  *     || any-ws-ready)
1513  * </code>
1514  *
1515  * @param delay how long should we wait?
1516  * @param priority priority to use
1517  * @param rfd file descriptor we want to read (can be -1)
1518  * @param wfd file descriptors we want to write (can be -1)
1519  * @param task main function of the task
1520  * @param task_cls closure of @a task
1521  * @return unique task identifier for the job
1522  *         only valid until @a task is started!
1523  */
1524 #ifndef MINGW
1525 static struct GNUNET_SCHEDULER_Task *
1526 add_without_sets (struct GNUNET_TIME_Relative delay,
1527                   enum GNUNET_SCHEDULER_Priority priority,
1528                   const struct GNUNET_NETWORK_Handle *read_nh,
1529                   const struct GNUNET_NETWORK_Handle *write_nh,
1530                   const struct GNUNET_DISK_FileHandle *read_fh,
1531                   const struct GNUNET_DISK_FileHandle *write_fh,
1532                   //int rfd,
1533                   //int wfd,
1534                   GNUNET_SCHEDULER_TaskCallback task,
1535                   void *task_cls)
1536 {
1537   struct GNUNET_SCHEDULER_Task *t;
1538
1539   GNUNET_assert (NULL != active_task);
1540   GNUNET_assert (NULL != task);
1541   t= initFdInfo (read_nh, write_nh, read_fh, write_fh);
1542
1543   t->callback = task;
1544   t->callback_cls = task_cls;
1545 #if DEBUG_FDS
1546   if (-1 != rfd)
1547   {
1548     int flags = fcntl (rfd, F_GETFD);
1549
1550     if ((flags == -1) && (errno == EBADF))
1551     {
1552       LOG (GNUNET_ERROR_TYPE_ERROR,
1553            "Got invalid file descriptor %d!\n",
1554            rfd);
1555       init_backtrace (t);
1556       GNUNET_assert (0);
1557     }
1558   }
1559   if (-1 != wfd)
1560   {
1561     int flags = fcntl (wfd, F_GETFD);
1562
1563     if (flags == -1 && errno == EBADF)
1564     {
1565       LOG (GNUNET_ERROR_TYPE_ERROR,
1566            "Got invalid file descriptor %d!\n",
1567            wfd);
1568       init_backtrace (t);
1569       GNUNET_assert (0);
1570     }
1571   }
1572 #endif
1573
1574 #if PROFILE_DELAYS
1575   t->start_time = GNUNET_TIME_absolute_get ();
1576 #endif
1577   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1578   t->priority = check_priority ((priority == GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority : priority);
1579   t->lifeness = current_lifeness;
1580
1581
1582
1583   scheduler_multi_function_call(t, scheduler_driver->add);
1584
1585   max_priority_added = GNUNET_MAX (max_priority_added,
1586                                    t->priority);
1587   LOG (GNUNET_ERROR_TYPE_DEBUG,
1588        "Adding task %p\n",
1589        t);
1590   init_backtrace (t);
1591   return t;
1592 }
1593 #endif
1594
1595
1596 /**
1597  * Schedule a new task to be run with a specified delay or when the
1598  * specified file descriptor is ready for reading.  The delay can be
1599  * used as a timeout on the socket being ready.  The task will be
1600  * scheduled for execution once either the delay has expired or the
1601  * socket operation is ready.  It will be run with the DEFAULT priority.
1602  *
1603  * @param delay when should this operation time out?
1604  * @param rfd read file-descriptor
1605  * @param task main function of the task
1606  * @param task_cls closure of @a task
1607  * @return unique task identifier for the job
1608  *         only valid until @a task is started!
1609  */
1610 struct GNUNET_SCHEDULER_Task *
1611 GNUNET_SCHEDULER_add_read_net (struct GNUNET_TIME_Relative delay,
1612                                struct GNUNET_NETWORK_Handle *rfd,
1613                                GNUNET_SCHEDULER_TaskCallback task,
1614                                void *task_cls)
1615 {
1616   return GNUNET_SCHEDULER_add_read_net_with_priority (delay,
1617                   GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1618                   rfd, task, task_cls);
1619 }
1620
1621
1622 /**
1623  * Schedule a new task to be run with a specified priority and to be
1624  * run after the specified delay or when the specified file descriptor
1625  * is ready for reading.  The delay can be used as a timeout on the
1626  * socket being ready.  The task will be scheduled for execution once
1627  * either the delay has expired or the socket operation is ready.  It
1628  * will be run with the DEFAULT priority.
1629  *
1630  * @param delay when should this operation time out?
1631  * @param priority priority to use for the task
1632  * @param rfd read file-descriptor
1633  * @param task main function of the task
1634  * @param task_cls closure of @a task
1635  * @return unique task identifier for the job
1636  *         only valid until @a task is started!
1637  */
1638 struct GNUNET_SCHEDULER_Task *
1639 GNUNET_SCHEDULER_add_read_net_with_priority (struct GNUNET_TIME_Relative delay,
1640                enum GNUNET_SCHEDULER_Priority priority,
1641                struct GNUNET_NETWORK_Handle *rfd,
1642                GNUNET_SCHEDULER_TaskCallback task,
1643                                              void *task_cls)
1644 {
1645   return GNUNET_SCHEDULER_add_net_with_priority (delay, priority,
1646                                                  rfd,
1647                                                  GNUNET_YES,
1648                                                  GNUNET_NO,
1649                                                  task, task_cls);
1650 }
1651
1652
1653 /**
1654  * Schedule a new task to be run with a specified delay or when the
1655  * specified file descriptor is ready for writing.  The delay can be
1656  * used as a timeout on the socket being ready.  The task will be
1657  * scheduled for execution once either the delay has expired or the
1658  * socket operation is ready.  It will be run with the priority of
1659  * the calling task.
1660  *
1661  * @param delay when should this operation time out?
1662  * @param wfd write file-descriptor
1663  * @param task main function of the task
1664  * @param task_cls closure of @a task
1665  * @return unique task identifier for the job
1666  *         only valid until @a task is started!
1667  */
1668 struct GNUNET_SCHEDULER_Task *
1669 GNUNET_SCHEDULER_add_write_net (struct GNUNET_TIME_Relative delay,
1670                                 struct GNUNET_NETWORK_Handle *wfd,
1671                                 GNUNET_SCHEDULER_TaskCallback task,
1672                                 void *task_cls)
1673 {
1674   return GNUNET_SCHEDULER_add_net_with_priority (delay,
1675                                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1676                                                  wfd,
1677                                                  GNUNET_NO, GNUNET_YES,
1678                                                  task, task_cls);
1679 }
1680
1681 /**
1682  * Schedule a new task to be run with a specified delay or when the
1683  * specified file descriptor is ready.  The delay can be
1684  * used as a timeout on the socket being ready.  The task will be
1685  * scheduled for execution once either the delay has expired or the
1686  * socket operation is ready.
1687  *
1688  * @param delay when should this operation time out?
1689  * @param priority priority of the task
1690  * @param fd file-descriptor
1691  * @param on_read whether to poll the file-descriptor for readability
1692  * @param on_write whether to poll the file-descriptor for writability
1693  * @param task main function of the task
1694  * @param task_cls closure of task
1695  * @return unique task identifier for the job
1696  *         only valid until "task" is started!
1697  */
1698 struct GNUNET_SCHEDULER_Task *
1699 GNUNET_SCHEDULER_add_net_with_priority  (struct GNUNET_TIME_Relative delay,
1700                                          enum GNUNET_SCHEDULER_Priority priority,
1701                                          struct GNUNET_NETWORK_Handle *fd,
1702                                          int on_read,
1703                                          int on_write,
1704                                          GNUNET_SCHEDULER_TaskCallback task,
1705                                          void *task_cls)
1706 {
1707 #if MINGW
1708   struct GNUNET_NETWORK_FDSet *s;
1709   struct GNUNET_SCHEDULER_Task * ret;
1710
1711   GNUNET_assert (NULL != fd);
1712   s = GNUNET_NETWORK_fdset_create ();
1713   GNUNET_NETWORK_fdset_set (s, fd);
1714   ret = GNUNET_SCHEDULER_add_select (
1715       priority, delay,
1716       on_read  ? s : NULL,
1717       on_write ? s : NULL,
1718       task, task_cls);
1719   GNUNET_NETWORK_fdset_destroy (s);
1720   return ret;
1721 #else
1722   GNUNET_assert (on_read || on_write);
1723   GNUNET_assert (GNUNET_NETWORK_get_fd (fd) >= 0);
1724   return add_without_sets (delay, priority,
1725                            on_read  ? fd : NULL,
1726                            on_write ? fd : NULL,
1727                            NULL,
1728                            NULL,
1729                            task, task_cls);
1730 #endif
1731 }
1732
1733
1734 /**
1735  * Schedule a new task to be run with a specified delay or when the
1736  * specified file descriptor is ready for reading.  The delay can be
1737  * used as a timeout on the socket being ready.  The task will be
1738  * scheduled for execution once either the delay has expired or the
1739  * socket operation is ready. It will be run with the DEFAULT priority.
1740  *
1741  * @param delay when should this operation time out?
1742  * @param rfd read file-descriptor
1743  * @param task main function of the task
1744  * @param task_cls closure of @a task
1745  * @return unique task identifier for the job
1746  *         only valid until @a task is started!
1747  */
1748 struct GNUNET_SCHEDULER_Task *
1749 GNUNET_SCHEDULER_add_read_file (struct GNUNET_TIME_Relative delay,
1750                                 const struct GNUNET_DISK_FileHandle *rfd,
1751                                 GNUNET_SCHEDULER_TaskCallback task, void *task_cls)
1752 {
1753   return GNUNET_SCHEDULER_add_file_with_priority (
1754       delay, GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1755       rfd, GNUNET_YES, GNUNET_NO,
1756       task, task_cls);
1757 }
1758
1759
1760 /**
1761  * Schedule a new task to be run with a specified delay or when the
1762  * specified file descriptor is ready for writing.  The delay can be
1763  * used as a timeout on the socket being ready.  The task will be
1764  * scheduled for execution once either the delay has expired or the
1765  * socket operation is ready. It will be run with the DEFAULT priority.
1766  *
1767  * @param delay when should this operation time out?
1768  * @param wfd write file-descriptor
1769  * @param task main function of the task
1770  * @param task_cls closure of @a task
1771  * @return unique task identifier for the job
1772  *         only valid until @a task is started!
1773  */
1774 struct GNUNET_SCHEDULER_Task *
1775 GNUNET_SCHEDULER_add_write_file (struct GNUNET_TIME_Relative delay,
1776                                  const struct GNUNET_DISK_FileHandle *wfd,
1777                                  GNUNET_SCHEDULER_TaskCallback task, void *task_cls)
1778 {
1779   return GNUNET_SCHEDULER_add_file_with_priority (
1780       delay, GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1781       wfd, GNUNET_NO, GNUNET_YES,
1782       task, task_cls);
1783 }
1784
1785
1786 /**
1787  * Schedule a new task to be run with a specified delay or when the
1788  * specified file descriptor is ready.  The delay can be
1789  * used as a timeout on the socket being ready.  The task will be
1790  * scheduled for execution once either the delay has expired or the
1791  * socket operation is ready.
1792  *
1793  * @param delay when should this operation time out?
1794  * @param priority priority of the task
1795  * @param fd file-descriptor
1796  * @param on_read whether to poll the file-descriptor for readability
1797  * @param on_write whether to poll the file-descriptor for writability
1798  * @param task main function of the task
1799  * @param task_cls closure of @a task
1800  * @return unique task identifier for the job
1801  *         only valid until @a task is started!
1802  */
1803 struct GNUNET_SCHEDULER_Task *
1804 GNUNET_SCHEDULER_add_file_with_priority (struct GNUNET_TIME_Relative delay,
1805                                          enum GNUNET_SCHEDULER_Priority priority,
1806                                          const struct GNUNET_DISK_FileHandle *fd,
1807                                          int on_read, int on_write,
1808                                          GNUNET_SCHEDULER_TaskCallback task, void *task_cls)
1809 {
1810 #if MINGW
1811   struct GNUNET_NETWORK_FDSet *s;
1812   struct GNUNET_SCHEDULER_Task * ret;
1813
1814   GNUNET_assert (NULL != fd);
1815   s = GNUNET_NETWORK_fdset_create ();
1816   GNUNET_NETWORK_fdset_handle_set (s, fd);
1817   ret = GNUNET_SCHEDULER_add_select (
1818       priority, delay,
1819       on_read  ? s : NULL,
1820       on_write ? s : NULL,
1821       task, task_cls);
1822   GNUNET_NETWORK_fdset_destroy (s);
1823   return ret;
1824 #else
1825   GNUNET_assert (on_read || on_write);
1826   GNUNET_assert(fd->fd >= 0);
1827   return add_without_sets (delay, priority,
1828                            NULL,
1829                            NULL,
1830                            on_read ? fd : NULL,
1831                            on_write ? fd : NULL,
1832                            task, task_cls);
1833 #endif
1834 }
1835
1836
1837 /**
1838  * Schedule a new task to be run with a specified delay or when any of
1839  * the specified file descriptor sets is ready.  The delay can be used
1840  * as a timeout on the socket(s) being ready.  The task will be
1841  * scheduled for execution once either the delay has expired or any of
1842  * the socket operations is ready.  This is the most general
1843  * function of the "add" family.  Note that the "prerequisite_task"
1844  * must be satisfied in addition to any of the other conditions.  In
1845  * other words, the task will be started when
1846  * <code>
1847  * (prerequisite-run)
1848  * && (delay-ready
1849  *     || any-rs-ready
1850  *     || any-ws-ready) )
1851  * </code>
1852  *
1853  * @param prio how important is this task?
1854  * @param delay how long should we wait?
1855  * @param rs set of file descriptors we want to read (can be NULL)
1856  * @param ws set of file descriptors we want to write (can be NULL)
1857  * @param task main function of the task
1858  * @param task_cls closure of @a task
1859  * @return unique task identifier for the job
1860  *         only valid until @a task is started!
1861  */
1862 struct GNUNET_SCHEDULER_Task *
1863 GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio,
1864                              struct GNUNET_TIME_Relative delay,
1865                              const struct GNUNET_NETWORK_FDSet *rs,
1866                              const struct GNUNET_NETWORK_FDSet *ws,
1867                              GNUNET_SCHEDULER_TaskCallback task,
1868                              void *task_cls)
1869 {
1870   struct GNUNET_SCHEDULER_Task *t;
1871
1872   if ( (NULL == rs) &&
1873        (NULL == ws) )
1874     return GNUNET_SCHEDULER_add_delayed_with_priority (delay,
1875                                                        prio,
1876                                                        task,
1877                                                        task_cls);
1878   GNUNET_assert (NULL != active_task);
1879   GNUNET_assert (NULL != task);
1880   t = GNUNET_new (struct GNUNET_SCHEDULER_Task);
1881   t->callback = task;
1882   t->callback_cls = task_cls;
1883   t->read_fd = -1;
1884   t->write_fd = -1;
1885   if (NULL != rs)
1886   {
1887     t->read_set = GNUNET_NETWORK_fdset_create ();
1888     GNUNET_NETWORK_fdset_copy (t->read_set, rs);
1889   }
1890   if (NULL != ws)
1891   {
1892     t->write_set = GNUNET_NETWORK_fdset_create ();
1893     GNUNET_NETWORK_fdset_copy (t->write_set, ws);
1894   }
1895 #if PROFILE_DELAYS
1896   t->start_time = GNUNET_TIME_absolute_get ();
1897 #endif
1898   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1899   t->priority =
1900       check_priority ((prio ==
1901                        GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority :
1902                       prio);
1903   t->lifeness = current_lifeness;
1904
1905   scheduler_multi_function_call(t, scheduler_driver->add);
1906
1907   max_priority_added = GNUNET_MAX (max_priority_added,
1908            t->priority);
1909   LOG (GNUNET_ERROR_TYPE_DEBUG,
1910        "Adding task %p\n",
1911        t);
1912   init_backtrace (t);
1913   return t;
1914 }
1915
1916
1917 /**
1918  * Function used by event-loop implementations to signal the scheduler
1919  * that a particular @a task is ready due to an event of type @a et.
1920  *
1921  * This function will then queue the task to notify the application
1922  * that the task is ready (with the respective priority).
1923  *
1924  * @param task the task that is ready, NULL for wake up calls
1925  * @param et information about why the task is ready
1926  */
1927 void
1928 GNUNET_SCHEDULER_task_ready (struct GNUNET_SCHEDULER_Task *task,
1929            enum GNUNET_SCHEDULER_EventType et)
1930 {
1931   enum GNUNET_SCHEDULER_Reason reason;
1932   struct GNUNET_TIME_Absolute now;
1933
1934   now = GNUNET_TIME_absolute_get ();
1935   reason = task->reason;
1936   if (now.abs_value_us >= task->timeout.abs_value_us)
1937     reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
1938   if ( (0 == (reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
1939        (0 != (GNUNET_SCHEDULER_ET_IN & et)) )
1940     reason |= GNUNET_SCHEDULER_REASON_READ_READY;
1941   if ( (0 == (reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) &&
1942        (0 != (GNUNET_SCHEDULER_ET_OUT & et)) )
1943     reason |= GNUNET_SCHEDULER_REASON_WRITE_READY;
1944   reason |= GNUNET_SCHEDULER_REASON_PREREQ_DONE;
1945   task->reason = reason;
1946   task->fds = &task->fdx;
1947   task->fdx.et = et;
1948   task->fds_len = 1;
1949   queue_ready_task (task);
1950 }
1951
1952
1953 /**
1954  * Function called by the driver to tell the scheduler to run some of
1955  * the tasks that are ready.  This function may return even though
1956  * there are tasks left to run just to give other tasks a chance as
1957  * well.  If we return #GNUNET_YES, the driver should call this
1958  * function again as soon as possible, while if we return #GNUNET_NO
1959  * it must block until the operating system has more work as the
1960  * scheduler has no more work to do right now.
1961  *
1962  * @param sh scheduler handle that was given to the `loop`
1963  * @return #GNUNET_OK if there are more tasks that are ready,
1964  *          and thus we would like to run more (yield to avoid
1965  *          blocking other activities for too long)
1966  *         #GNUNET_NO if we are done running tasks (yield to block)
1967  *         #GNUNET_SYSERR on error
1968  */
1969 int
1970 GNUNET_SCHEDULER_run_from_driver (struct GNUNET_SCHEDULER_Handle *sh)
1971 {
1972   enum GNUNET_SCHEDULER_Priority p;
1973   struct GNUNET_SCHEDULER_Task *pos;
1974   struct GNUNET_TIME_Absolute now;
1975
1976   /* check for tasks that reached the timeout! */
1977   now = GNUNET_TIME_absolute_get ();
1978   while (NULL != (pos = pending_timeout_head))
1979   {
1980     if (now.abs_value_us >= pos->timeout.abs_value_us)
1981       pos->reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
1982     if (0 == pos->reason)
1983       break;
1984     GNUNET_CONTAINER_DLL_remove (pending_timeout_head,
1985                                  pending_timeout_tail,
1986                                  pos);
1987     scheduler_driver->set_wakeup(scheduler_driver->cls,pending_timeout_head->timeout);
1988     if (pending_timeout_last == pos)
1989       pending_timeout_last = NULL;
1990     queue_ready_task (pos);
1991   }
1992
1993   if (0 == ready_count)
1994     return GNUNET_NO;
1995
1996   /* find out which task priority level we are going to
1997      process this time */
1998   max_priority_added = GNUNET_SCHEDULER_PRIORITY_KEEP;
1999   GNUNET_assert (NULL == ready_head[GNUNET_SCHEDULER_PRIORITY_KEEP]);
2000   /* yes, p>0 is correct, 0 is "KEEP" which should
2001    * always be an empty queue (see assertion)! */
2002   for (p = GNUNET_SCHEDULER_PRIORITY_COUNT - 1; p > 0; p--)
2003   {
2004     pos = ready_head[p];
2005     if (NULL != pos)
2006       break;
2007   }
2008   GNUNET_assert (NULL != pos);        /* ready_count wrong? */
2009
2010   /* process all tasks at this priority level, then yield */
2011   while (NULL != (pos = ready_head[p]))
2012   {
2013     GNUNET_CONTAINER_DLL_remove (ready_head[p],
2014          ready_tail[p],
2015          pos);
2016     ready_count--;
2017     current_priority = pos->priority;
2018     current_lifeness = pos->lifeness;
2019     active_task = pos;
2020 #if PROFILE_DELAYS
2021     if (GNUNET_TIME_absolute_get_duration (pos->start_time).rel_value_us >
2022   DELAY_THRESHOLD.rel_value_us)
2023     {
2024       LOG (GNUNET_ERROR_TYPE_DEBUG,
2025      "Task %p took %s to be scheduled\n",
2026      pos,
2027      GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pos->start_time),
2028                GNUNET_YES));
2029     }
2030 #endif
2031     tc.reason = pos->reason;
2032     GNUNET_NETWORK_fdset_zero (sh->rs);
2033     GNUNET_NETWORK_fdset_zero (sh->ws);
2034     tc.fds_len = pos->fds_len;
2035     tc.fds = pos->fds;
2036     tc.read_ready = (NULL == pos->read_set) ? sh->rs : pos->read_set;
2037     if ( (-1 != pos->read_fd) &&
2038    (0 != (pos->reason & GNUNET_SCHEDULER_REASON_READ_READY)) )
2039       GNUNET_NETWORK_fdset_set_native (sh->rs,
2040                pos->read_fd);
2041     tc.write_ready = (NULL == pos->write_set) ? sh->ws : pos->write_set;
2042     if ((-1 != pos->write_fd) &&
2043   (0 != (pos->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)))
2044       GNUNET_NETWORK_fdset_set_native (sh->ws,
2045                pos->write_fd);
2046     LOG (GNUNET_ERROR_TYPE_DEBUG,
2047    "Running task: %p\n",
2048    pos);
2049     pos->callback (pos->callback_cls);
2050     active_task = NULL;
2051     dump_backtrace (pos);
2052     destroy_task (pos);
2053     tasks_run++;
2054   }
2055   if (0 == ready_count)
2056     return GNUNET_NO;
2057   return GNUNET_OK;
2058 }
2059
2060
2061 /**
2062  * Initialize and run scheduler.  This function will return when all
2063  * tasks have completed.  On systems with signals, receiving a SIGTERM
2064  * (and other similar signals) will cause #GNUNET_SCHEDULER_shutdown
2065  * to be run after the active task is complete.  As a result, SIGTERM
2066  * causes all shutdown tasks to be scheduled with reason
2067  * #GNUNET_SCHEDULER_REASON_SHUTDOWN.  (However, tasks added
2068  * afterwards will execute normally!).  Note that any particular
2069  * signal will only shut down one scheduler; applications should
2070  * always only create a single scheduler.
2071  *
2072  * @param driver drive to use for the event loop
2073  * @param task task to run first (and immediately)
2074  * @param task_cls closure of @a task
2075  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2076  */
2077 int
2078 GNUNET_SCHEDULER_run_with_driver (const struct GNUNET_SCHEDULER_Driver *driver,
2079           GNUNET_SCHEDULER_TaskCallback task,
2080           void *task_cls)
2081 {
2082   int ret;
2083   struct GNUNET_SCHEDULER_Handle sh;
2084   struct GNUNET_SIGNAL_Context *shc_int;
2085   struct GNUNET_SIGNAL_Context *shc_term;
2086 #if (SIGTERM != GNUNET_TERM_SIG)
2087   struct GNUNET_SIGNAL_Context *shc_gterm;
2088 #endif
2089 #ifndef MINGW
2090   struct GNUNET_SIGNAL_Context *shc_quit;
2091   struct GNUNET_SIGNAL_Context *shc_hup;
2092   struct GNUNET_SIGNAL_Context *shc_pipe;
2093 #endif
2094   struct GNUNET_SCHEDULER_Task tsk;
2095   const struct GNUNET_DISK_FileHandle *pr;
2096   scheduler_driver = driver;
2097
2098   /* general set-up */
2099   GNUNET_assert (NULL == active_task);
2100   GNUNET_assert (NULL == shutdown_pipe_handle);
2101   shutdown_pipe_handle = GNUNET_DISK_pipe (GNUNET_NO,
2102                                            GNUNET_NO,
2103                                            GNUNET_NO,
2104                                            GNUNET_NO);
2105   GNUNET_assert (NULL != shutdown_pipe_handle);
2106   pr = GNUNET_DISK_pipe_handle (shutdown_pipe_handle,
2107                                 GNUNET_DISK_PIPE_END_READ);
2108   GNUNET_assert (NULL != pr);
2109   my_pid = getpid ();
2110
2111   /* install signal handlers */
2112   LOG (GNUNET_ERROR_TYPE_DEBUG,
2113        "Registering signal handlers\n");
2114   shc_int = GNUNET_SIGNAL_handler_install (SIGINT,
2115              &sighandler_shutdown);
2116   shc_term = GNUNET_SIGNAL_handler_install (SIGTERM,
2117               &sighandler_shutdown);
2118 #if (SIGTERM != GNUNET_TERM_SIG)
2119   shc_gterm = GNUNET_SIGNAL_handler_install (GNUNET_TERM_SIG,
2120                &sighandler_shutdown);
2121 #endif
2122 #ifndef MINGW
2123   shc_pipe = GNUNET_SIGNAL_handler_install (SIGPIPE,
2124               &sighandler_pipe);
2125   shc_quit = GNUNET_SIGNAL_handler_install (SIGQUIT,
2126               &sighandler_shutdown);
2127   shc_hup = GNUNET_SIGNAL_handler_install (SIGHUP,
2128              &sighandler_shutdown);
2129 #endif
2130
2131   /* Setup initial tasks */
2132   current_priority = GNUNET_SCHEDULER_PRIORITY_DEFAULT;
2133   current_lifeness = GNUNET_YES;
2134   memset (&tsk,
2135     0,
2136     sizeof (tsk));
2137   active_task = &tsk;
2138   tsk.sh = &sh;
2139   GNUNET_SCHEDULER_add_with_reason_and_priority (task,
2140                                                  task_cls,
2141                                                  GNUNET_SCHEDULER_REASON_STARTUP,
2142                                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT);
2143   GNUNET_SCHEDULER_add_now_with_lifeness (GNUNET_NO,
2144                                           &GNUNET_OS_install_parent_control_handler,
2145                                           NULL);
2146   active_task = NULL;
2147   driver->set_wakeup (driver->cls,
2148           GNUNET_TIME_absolute_get ());
2149
2150   /* begin main event loop */
2151   sh.rs = GNUNET_NETWORK_fdset_create ();
2152   sh.ws = GNUNET_NETWORK_fdset_create ();
2153   GNUNET_NETWORK_fdset_handle_set (sh.rs, pr);
2154   sh.driver = driver;
2155   ret = driver->loop (driver->cls,
2156           &sh);
2157   GNUNET_NETWORK_fdset_destroy (sh.rs);
2158   GNUNET_NETWORK_fdset_destroy (sh.ws);
2159
2160   /* uninstall signal handlers */
2161   GNUNET_SIGNAL_handler_uninstall (shc_int);
2162   GNUNET_SIGNAL_handler_uninstall (shc_term);
2163 #if (SIGTERM != GNUNET_TERM_SIG)
2164   GNUNET_SIGNAL_handler_uninstall (shc_gterm);
2165 #endif
2166 #ifndef MINGW
2167   GNUNET_SIGNAL_handler_uninstall (shc_pipe);
2168   GNUNET_SIGNAL_handler_uninstall (shc_quit);
2169   GNUNET_SIGNAL_handler_uninstall (shc_hup);
2170 #endif
2171   GNUNET_DISK_pipe_close (shutdown_pipe_handle);
2172   shutdown_pipe_handle = NULL;
2173   return ret;
2174 }
2175
2176 int
2177 select_add(void *cls,
2178  struct GNUNET_SCHEDULER_Task *task,
2179  struct GNUNET_SCHEDULER_FdInfo *fdi){
2180
2181   GNUNET_CONTAINER_DLL_insert (pending_head,
2182                                pending_tail,
2183                                task);
2184
2185 }
2186
2187 int
2188 select_del(void *cls,
2189  struct GNUNET_SCHEDULER_Task *task,
2190  struct GNUNET_SCHEDULER_FdInfo *fdi){
2191
2192   GNUNET_CONTAINER_DLL_remove (pending_head,
2193                                pending_tail,
2194                                task);
2195
2196 }
2197
2198
2199 int
2200 select_loop(void *cls,
2201         struct GNUNET_SCHEDULER_Handle *sh){
2202
2203   while_live(sh->rs, sh->ws);
2204
2205 }
2206
2207 static void
2208 select_set_wakeup(void *cls,
2209                    struct GNUNET_TIME_Absolute dt){
2210
2211
2212
2213 }
2214
2215
2216 /**
2217  * Obtain the driver for using select() as the event loop.
2218  *
2219  * @return NULL on error
2220  */
2221 const struct GNUNET_SCHEDULER_Driver *
2222 GNUNET_SCHEDULER_driver_select ()
2223 {
2224
2225   struct GNUNET_SCHEDULER_Driver *select_driver;
2226
2227   select_driver = GNUNET_new (struct GNUNET_SCHEDULER_Driver);
2228
2229   select_driver->loop = &select_loop;
2230   select_driver->add = &select_add;
2231   select_driver->del = &select_del;
2232   select_driver->set_wakeup = &select_set_wakeup;
2233
2234
2235   return select_driver;
2236 }
2237
2238
2239 /* end of scheduler.c */