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