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