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