070c0daa8e14c7d38bae83966d7f5c4f42885810
[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 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   unsigned int busy_wait_warning;
947
948
949
950   GNUNET_assert (NULL == active_task);
951   rs = GNUNET_NETWORK_fdset_create ();
952   ws = GNUNET_NETWORK_fdset_create ();
953   GNUNET_assert (NULL == shutdown_pipe_handle);
954   shutdown_pipe_handle = GNUNET_DISK_pipe (GNUNET_NO,
955                                            GNUNET_NO,
956                                            GNUNET_NO,
957                                            GNUNET_NO);
958   GNUNET_assert (NULL != shutdown_pipe_handle);
959
960   my_pid = getpid ();
961   LOG (GNUNET_ERROR_TYPE_DEBUG,
962        "Registering signal handlers\n");
963   shc_int = GNUNET_SIGNAL_handler_install (SIGINT,
964              &sighandler_shutdown);
965   shc_term = GNUNET_SIGNAL_handler_install (SIGTERM,
966               &sighandler_shutdown);
967 #if (SIGTERM != GNUNET_TERM_SIG)
968   shc_gterm = GNUNET_SIGNAL_handler_install (GNUNET_TERM_SIG,
969                &sighandler_shutdown);
970 #endif
971 #ifndef MINGW
972   shc_pipe = GNUNET_SIGNAL_handler_install (SIGPIPE,
973               &sighandler_pipe);
974   shc_quit = GNUNET_SIGNAL_handler_install (SIGQUIT,
975               &sighandler_shutdown);
976   shc_hup = GNUNET_SIGNAL_handler_install (SIGHUP,
977              &sighandler_shutdown);
978 #endif
979   current_priority = GNUNET_SCHEDULER_PRIORITY_DEFAULT;
980   current_lifeness = GNUNET_YES;
981   GNUNET_SCHEDULER_add_with_reason_and_priority (task,
982                                                  task_cls,
983                                                  GNUNET_SCHEDULER_REASON_STARTUP,
984                                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT);
985   active_task = (void *) (long) -1;     /* force passing of sanity check */
986   GNUNET_SCHEDULER_add_now_with_lifeness (GNUNET_NO,
987                                           &GNUNET_OS_install_parent_control_handler,
988                                           NULL);
989   active_task = NULL;
990
991
992   while_live(rs, ws);
993   GNUNET_SIGNAL_handler_uninstall (shc_int);
994   GNUNET_SIGNAL_handler_uninstall (shc_term);
995 #if (SIGTERM != GNUNET_TERM_SIG)
996   GNUNET_SIGNAL_handler_uninstall (shc_gterm);
997 #endif
998 #ifndef MINGW
999   GNUNET_SIGNAL_handler_uninstall (shc_pipe);
1000   GNUNET_SIGNAL_handler_uninstall (shc_quit);
1001   GNUNET_SIGNAL_handler_uninstall (shc_hup);
1002 #endif
1003   GNUNET_DISK_pipe_close (shutdown_pipe_handle);
1004   shutdown_pipe_handle = NULL;
1005   GNUNET_NETWORK_fdset_destroy (rs);
1006   GNUNET_NETWORK_fdset_destroy (ws);
1007 }
1008
1009
1010 /**
1011  * Obtain the task context, giving the reason why the current task was
1012  * started.
1013  *
1014  * @return current tasks' scheduler context
1015  */
1016 const struct GNUNET_SCHEDULER_TaskContext *
1017 GNUNET_SCHEDULER_get_task_context ()
1018 {
1019   GNUNET_assert (NULL != active_task);
1020   return &tc;
1021 }
1022
1023
1024 /**
1025  * Get information about the current load of this scheduler.  Use this
1026  * function to determine if an elective task should be added or simply
1027  * dropped (if the decision should be made based on the number of
1028  * tasks ready to run).
1029  *
1030  * @param p priority level to look at
1031  * @return number of tasks pending right now
1032  */
1033 unsigned int
1034 GNUNET_SCHEDULER_get_load (enum GNUNET_SCHEDULER_Priority p)
1035 {
1036   struct GNUNET_SCHEDULER_Task *pos;
1037   unsigned int ret;
1038
1039   GNUNET_assert (NULL != active_task);
1040   if (p == GNUNET_SCHEDULER_PRIORITY_COUNT)
1041     return ready_count;
1042   if (p == GNUNET_SCHEDULER_PRIORITY_KEEP)
1043     p = current_priority;
1044   ret = 0;
1045   for (pos = ready_head[check_priority (p)]; NULL != pos; pos = pos->next)
1046     ret++;
1047   return ret;
1048 }
1049
1050
1051 /**
1052  * Cancel the task with the specified identifier.
1053  * The task must not yet have run.
1054  *
1055  * @param task id of the task to cancel
1056  * @return original closure of the task
1057  */
1058 void
1059 initFdInfo(struct GNUNET_SCHEDULER_Task *task,
1060            struct GNUNET_NETWORK_Handle *read_nh,
1061            struct GNUNET_NETWORK_Handle *write_nh,
1062            struct GNUNET_DISK_FileHandle *read_fh,
1063            struct GNUNET_DISK_FileHandle *write_fh)
1064 {
1065   // either only network handles or only file handles are allowed
1066   GNUNET_assert (!((NULL != read_nh || NULL != write_nh) && (NULL != read_fh || NULL != write_fh)));
1067
1068   if (NULL != read_nh && NULL != write_nh)
1069   {
1070     t->fds_len = 2;
1071     t->fds =
1072       GNUNET_new_array (2, struct GNUNET_SCHEDULER_FdInfo);
1073     struct GNUNET_SCHEDULER_FdInfo *read_fdi = t->fds;
1074     struct GNUENT_SCHEDULER_FdInfo *write_fdi = t->fds + 1;
1075     read_fdi->fd = read_nh;
1076     read_fdi->et = GNUNET_SCHEDULER_ET_IN;
1077     read_fdi->sock = GNUNET_NETWORK_get_fd (read_nh);
1078     write_fdi->fd = write_nh;
1079     write_fdi->et = GNUNET_SCHEDULER_ET_OUT;
1080     write_fdi->sock = GNUNET_NETWORK_get_fd (write_nh);
1081   }
1082   else if (NULL != read_fh && NULL != write_fh)
1083   {
1084     t->fds_len = 2;
1085     t->fds =
1086       GNUNET_new_array (2, struct GNUNET_SCHEDULER_FdInfo);
1087     struct GNUNET_SCHEDULER_FdInfo *read_fdi = t->fds;
1088     struct GNUENT_SCHEDULER_FdInfo *write_fdi = t->fds + 1;
1089     read_fdi->fh = read_fh;
1090     read_fdi->et = GNUNET_SCHEDULER_ET_IN;
1091     write_fdi->fh = write_fh;
1092     write_fdi->et = GNUNET_SCHEDULER_ET_OUT;
1093   }
1094   else if (NULL != read_nh)
1095   {
1096     struct GNUNET_SCHEDULER_FdInfo *read_fdi = &t->fdx;
1097     read_fdi->fd = read_nh;
1098     read_fdi->et = GNUNET_SCHEDULER_ET_IN;
1099     read_fdi->sock = GNUNET_NETWORK_get_fd (read_nh);
1100   }
1101   else if (NULL != write_nh)
1102   {
1103     struct GNUNET_SCHEDULER_FdInfo *write_fdi = &t->fdx;
1104     write_fdi->fd = write_nh;
1105     write_fdi->et = GNUNET_SCHEDULER_ET_OUT;
1106     write_fdi->sock = GNUNET_NETWORK_get_fd (write_nh);
1107   }
1108   else if (NULL != read_fh)
1109   {
1110     struct GNUNET_SCHEDULER_FdInfo *read_fdi = &t->fdx;
1111     read_fdi->fh = read_fh;
1112     read_fdi->et = GNUNET_SCHEDULER_ET_IN;
1113   }
1114   else if (NULL != write_fh)
1115   {
1116     struct GNUNET_SCHEDULER_FdInfo *write_fdi = &t->fdx;
1117     write_fdi->fh = write_fh;
1118     write_fdi->et = GNUNET_SCHEDULER_ET_OUT;
1119   }
1120 }
1121
1122 void *
1123 GNUNET_SCHEDULER_cancel (struct GNUNET_SCHEDULER_Task *task)
1124 {
1125   enum GNUNET_SCHEDULER_Priority p;
1126   void *ret;
1127   struct GNUNET_SCHEDULER_FdInfo *fdi;
1128
1129   GNUNET_assert ( (NULL != active_task) ||
1130       (GNUNET_NO == task->lifeness) );
1131   if (! task->in_ready_list)
1132   {
1133     if ( (-1 == task->read_fd) &&
1134          (-1 == task->write_fd) &&
1135          (NULL == task->read_set) &&
1136          (NULL == task->write_set) )
1137     {
1138       if (GNUNET_YES == task->on_shutdown)
1139   GNUNET_CONTAINER_DLL_remove (shutdown_head,
1140              shutdown_tail,
1141              task);
1142       else
1143   GNUNET_CONTAINER_DLL_remove (pending_timeout_head,
1144              pending_timeout_tail,
1145              task);
1146       if (task == pending_timeout_last)
1147         pending_timeout_last = NULL;
1148     }
1149     else
1150     {
1151       /*GNUNET_CONTAINER_DLL_remove (pending_head,
1152                                    pending_tail,
1153                                    task);*/
1154       fdi = GNUNET_new (struct GNUNET_SCHEDULER_FdInfo);
1155       initFdInfo(fdi, task);
1156       scheduler_driver->del(scheduler_driver->cls, task, fdi);
1157     }
1158   }
1159   else
1160   {
1161     p = check_priority (task->priority);
1162     GNUNET_CONTAINER_DLL_remove (ready_head[p],
1163                                  ready_tail[p],
1164                                  task);
1165     ready_count--;
1166   }
1167   ret = task->callback_cls;
1168   LOG (GNUNET_ERROR_TYPE_DEBUG,
1169        "Canceling task %p\n",
1170        task);
1171   destroy_task (task);
1172   return ret;
1173 }
1174
1175
1176 /**
1177  * Initialize backtrace data for task @a t
1178  *
1179  * @param t task to initialize
1180  */
1181 static void
1182 init_backtrace (struct GNUNET_SCHEDULER_Task *t)
1183 {
1184 #if EXECINFO
1185   void *backtrace_array[MAX_TRACE_DEPTH];
1186
1187   t->num_backtrace_strings
1188     = backtrace (backtrace_array, MAX_TRACE_DEPTH);
1189   t->backtrace_strings =
1190       backtrace_symbols (backtrace_array,
1191        t->num_backtrace_strings);
1192   dump_backtrace (t);
1193 #endif
1194 }
1195
1196
1197 /**
1198  * Continue the current execution with the given function.  This is
1199  * similar to the other "add" functions except that there is no delay
1200  * and the reason code can be specified.
1201  *
1202  * @param task main function of the task
1203  * @param task_cls closure for @a task
1204  * @param reason reason for task invocation
1205  * @param priority priority to use for the task
1206  */
1207 void
1208 GNUNET_SCHEDULER_add_with_reason_and_priority (GNUNET_SCHEDULER_TaskCallback task,
1209                                                void *task_cls,
1210                                                enum GNUNET_SCHEDULER_Reason reason,
1211                                                enum GNUNET_SCHEDULER_Priority priority)
1212 {
1213   struct GNUNET_SCHEDULER_Task *t;
1214
1215   GNUNET_assert (NULL != task);
1216   GNUNET_assert ((NULL != active_task) ||
1217                  (GNUNET_SCHEDULER_REASON_STARTUP == reason));
1218   t = GNUNET_new (struct GNUNET_SCHEDULER_Task);
1219   t->read_fd = -1;
1220   t->write_fd = -1;
1221   t->callback = task;
1222   t->callback_cls = task_cls;
1223 #if PROFILE_DELAYS
1224   t->start_time = GNUNET_TIME_absolute_get ();
1225 #endif
1226   t->reason = reason;
1227   t->priority = priority;
1228   t->lifeness = current_lifeness;
1229   LOG (GNUNET_ERROR_TYPE_DEBUG,
1230        "Adding continuation task %p\n",
1231        t);
1232   init_backtrace (t);
1233   queue_ready_task (t);
1234 }
1235
1236
1237 /**
1238  * Schedule a new task to be run at the specified time.  The task
1239  * will be scheduled for execution at time @a at.
1240  *
1241  * @param at time when the operation should run
1242  * @param priority priority to use for the task
1243  * @param task main function of the task
1244  * @param task_cls closure of @a task
1245  * @return unique task identifier for the job
1246  *         only valid until @a task is started!
1247  */
1248 struct GNUNET_SCHEDULER_Task *
1249 GNUNET_SCHEDULER_add_at_with_priority (struct GNUNET_TIME_Absolute at,
1250                                        enum GNUNET_SCHEDULER_Priority priority,
1251                                        GNUNET_SCHEDULER_TaskCallback task,
1252                                        void *task_cls)
1253 {
1254   struct GNUNET_SCHEDULER_Task *t;
1255   struct GNUNET_SCHEDULER_Task *pos;
1256   struct GNUNET_SCHEDULER_Task *prev;
1257
1258   GNUNET_assert (NULL != active_task);
1259   GNUNET_assert (NULL != task);
1260   t = GNUNET_new (struct GNUNET_SCHEDULER_Task);
1261   t->callback = task;
1262   t->callback_cls = task_cls;
1263   t->read_fd = -1;
1264   t->write_fd = -1;
1265 #if PROFILE_DELAYS
1266   t->start_time = GNUNET_TIME_absolute_get ();
1267 #endif
1268   t->timeout = at;
1269   t->priority = priority;
1270   t->lifeness = current_lifeness;
1271   /* try tail first (optimization in case we are
1272    * appending to a long list of tasks with timeouts) */
1273   if ( (NULL == pending_timeout_head) ||
1274        (at.abs_value_us < pending_timeout_head->timeout.abs_value_us) )
1275   {
1276     GNUNET_CONTAINER_DLL_insert (pending_timeout_head,
1277                                  pending_timeout_tail,
1278                                  t);
1279   }
1280   else
1281   {
1282     /* first move from heuristic start backwards to before start time */
1283     prev = pending_timeout_last;
1284     while ( (NULL != prev) &&
1285             (prev->timeout.abs_value_us > t->timeout.abs_value_us) )
1286       prev = prev->prev;
1287     /* now, move from heuristic start (or head of list) forward to insertion point */
1288     if (NULL == prev)
1289       pos = pending_timeout_head;
1290     else
1291       pos = prev->next;
1292     while ( (NULL != pos) &&
1293             ( (pos->timeout.abs_value_us <= t->timeout.abs_value_us) ||
1294               (0 != pos->reason) ) )
1295     {
1296       prev = pos;
1297       pos = pos->next;
1298     }
1299     GNUNET_CONTAINER_DLL_insert_after (pending_timeout_head,
1300                                        pending_timeout_tail,
1301                                        prev,
1302                                        t);
1303   }
1304   /* finally, update heuristic insertion point to last insertion... */
1305   pending_timeout_last = t;
1306
1307   LOG (GNUNET_ERROR_TYPE_DEBUG,
1308        "Adding task: %p\n",
1309        t);
1310   init_backtrace (t);
1311   return t;
1312 }
1313
1314
1315 /**
1316  * Schedule a new task to be run with a specified delay.  The task
1317  * will be scheduled for execution once the delay has expired.
1318  *
1319  * @param delay when should this operation time out?
1320  * @param priority priority to use for the task
1321  * @param task main function of the task
1322  * @param task_cls closure of @a task
1323  * @return unique task identifier for the job
1324  *         only valid until @a task is started!
1325  */
1326 struct GNUNET_SCHEDULER_Task *
1327 GNUNET_SCHEDULER_add_delayed_with_priority (struct GNUNET_TIME_Relative delay,
1328               enum GNUNET_SCHEDULER_Priority priority,
1329               GNUNET_SCHEDULER_TaskCallback task,
1330                                             void *task_cls)
1331 {
1332   return GNUNET_SCHEDULER_add_at_with_priority (GNUNET_TIME_relative_to_absolute (delay),
1333                                                 priority,
1334                                                 task,
1335                                                 task_cls);
1336 }
1337
1338
1339 /**
1340  * Schedule a new task to be run with a specified priority.
1341  *
1342  * @param prio how important is the new task?
1343  * @param task main function of the task
1344  * @param task_cls closure of @a task
1345  * @return unique task identifier for the job
1346  *         only valid until @a task is started!
1347  */
1348 struct GNUNET_SCHEDULER_Task *
1349 GNUNET_SCHEDULER_add_with_priority (enum GNUNET_SCHEDULER_Priority prio,
1350                                     GNUNET_SCHEDULER_TaskCallback task,
1351                                     void *task_cls)
1352 {
1353   return GNUNET_SCHEDULER_add_delayed_with_priority (GNUNET_TIME_UNIT_ZERO,
1354                                                      prio,
1355                                                      task,
1356                                                      task_cls);
1357 }
1358
1359
1360 /**
1361  * Schedule a new task to be run at the specified time.  The task
1362  * will be scheduled for execution once specified time has been
1363  * reached. It will be run with the DEFAULT priority.
1364  *
1365  * @param at time at which this operation should run
1366  * @param task main function of the task
1367  * @param task_cls closure of @a task
1368  * @return unique task identifier for the job
1369  *         only valid until @a task is started!
1370  */
1371 struct GNUNET_SCHEDULER_Task *
1372 GNUNET_SCHEDULER_add_at (struct GNUNET_TIME_Absolute at,
1373                          GNUNET_SCHEDULER_TaskCallback task,
1374                          void *task_cls)
1375 {
1376   return GNUNET_SCHEDULER_add_at_with_priority (at,
1377                                                 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1378                                                 task,
1379                                                 task_cls);
1380 }
1381
1382
1383 /**
1384  * Schedule a new task to be run with a specified delay.  The task
1385  * will be scheduled for execution once the delay has expired. It
1386  * will be run with the DEFAULT priority.
1387  *
1388  * @param delay when should this operation time out?
1389  * @param task main function of the task
1390  * @param task_cls closure of @a task
1391  * @return unique task identifier for the job
1392  *         only valid until @a task is started!
1393  */
1394 struct GNUNET_SCHEDULER_Task *
1395 GNUNET_SCHEDULER_add_delayed (struct GNUNET_TIME_Relative delay,
1396                               GNUNET_SCHEDULER_TaskCallback task,
1397             void *task_cls)
1398 {
1399   return GNUNET_SCHEDULER_add_delayed_with_priority (delay,
1400                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1401                  task,
1402                                                      task_cls);
1403 }
1404
1405
1406 /**
1407  * Schedule a new task to be run as soon as possible.  Note that this
1408  * does not guarantee that this will be the next task that is being
1409  * run, as other tasks with higher priority (or that are already ready
1410  * to run) might get to run first.  Just as with delays, clients must
1411  * not rely on any particular order of execution between tasks
1412  * scheduled concurrently.
1413  *
1414  * The task will be run with the DEFAULT priority.
1415  *
1416  * @param task main function of the task
1417  * @param task_cls closure of @a task
1418  * @return unique task identifier for the job
1419  *         only valid until @a task is started!
1420  */
1421 struct GNUNET_SCHEDULER_Task *
1422 GNUNET_SCHEDULER_add_now (GNUNET_SCHEDULER_TaskCallback task,
1423         void *task_cls)
1424 {
1425   return GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_ZERO,
1426                task,
1427                task_cls);
1428 }
1429
1430
1431 /**
1432  * Schedule a new task to be run on shutdown, that is when a CTRL-C
1433  * signal is received, or when #GNUNET_SCHEDULER_shutdown() is being
1434  * invoked.
1435  *
1436  * @param task main function of the task
1437  * @param task_cls closure of @a task
1438  * @return unique task identifier for the job
1439  *         only valid until @a task is started!
1440  */
1441 struct GNUNET_SCHEDULER_Task *
1442 GNUNET_SCHEDULER_add_shutdown (GNUNET_SCHEDULER_TaskCallback task,
1443              void *task_cls)
1444 {
1445   struct GNUNET_SCHEDULER_Task *t;
1446
1447   GNUNET_assert (NULL != active_task);
1448   GNUNET_assert (NULL != task);
1449   t = GNUNET_new (struct GNUNET_SCHEDULER_Task);
1450   t->callback = task;
1451   t->callback_cls = task_cls;
1452   t->read_fd = -1;
1453   t->write_fd = -1;
1454 #if PROFILE_DELAYS
1455   t->start_time = GNUNET_TIME_absolute_get ();
1456 #endif
1457   t->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1458   t->priority = GNUNET_SCHEDULER_PRIORITY_SHUTDOWN;
1459   t->on_shutdown = GNUNET_YES;
1460   t->lifeness = GNUNET_YES;
1461   GNUNET_CONTAINER_DLL_insert (shutdown_head,
1462              shutdown_tail,
1463              t);
1464   LOG (GNUNET_ERROR_TYPE_DEBUG,
1465        "Adding task: %p\n",
1466        t);
1467   init_backtrace (t);
1468   return t;
1469 }
1470
1471
1472 /**
1473  * Schedule a new task to be run as soon as possible with the
1474  * (transitive) ignore-shutdown flag either explicitly set or
1475  * explicitly enabled.  This task (and all tasks created from it,
1476  * other than by another call to this function) will either count or
1477  * not count for the "lifeness" of the process.  This API is only
1478  * useful in a few special cases.
1479  *
1480  * @param lifeness #GNUNET_YES if the task counts for lifeness, #GNUNET_NO if not.
1481  * @param task main function of the task
1482  * @param task_cls closure of @a task
1483  * @return unique task identifier for the job
1484  *         only valid until @a task is started!
1485  */
1486 struct GNUNET_SCHEDULER_Task *
1487 GNUNET_SCHEDULER_add_now_with_lifeness (int lifeness,
1488                                         GNUNET_SCHEDULER_TaskCallback task,
1489                                         void *task_cls)
1490 {
1491   struct GNUNET_SCHEDULER_Task *ret;
1492
1493   ret = GNUNET_SCHEDULER_add_now (task, task_cls);
1494   ret->lifeness = lifeness;
1495   return ret;
1496 }
1497
1498
1499 /**
1500  * Schedule a new task to be run with a specified delay or when any of
1501  * the specified file descriptor sets is ready.  The delay can be used
1502  * as a timeout on the socket(s) being ready.  The task will be
1503  * scheduled for execution once either the delay has expired or any of
1504  * the socket operations is ready.  This is the most general
1505  * function of the "add" family.  Note that the "prerequisite_task"
1506  * must be satisfied in addition to any of the other conditions.  In
1507  * other words, the task will be started when
1508  * <code>
1509  * (prerequisite-run)
1510  * && (delay-ready
1511  *     || any-rs-ready
1512  *     || any-ws-ready)
1513  * </code>
1514  *
1515  * @param delay how long should we wait?
1516  * @param priority priority to use
1517  * @param rfd file descriptor we want to read (can be -1)
1518  * @param wfd file descriptors we want to write (can be -1)
1519  * @param task main function of the task
1520  * @param task_cls closure of @a task
1521  * @return unique task identifier for the job
1522  *         only valid until @a task is started!
1523  */
1524 #ifndef MINGW
1525 static struct GNUNET_SCHEDULER_Task *
1526 add_without_sets (struct GNUNET_TIME_Relative delay,
1527                   enum GNUNET_SCHEDULER_Priority priority,
1528                   struct GNUNET_NETWORK_Handle *read_nh,
1529                   struct GNUNET_NETWORK_Handle *write_nh,
1530                   struct GNUNET_DISK_FileHandle *read_fh,
1531                   struct GNUNET_DISK_FileHandle *write_fh,
1532                   //int rfd,
1533                   //int wfd,
1534                   GNUNET_SCHEDULER_TaskCallback task,
1535                   void *task_cls)
1536 {
1537   struct GNUNET_SCHEDULER_Task *t;
1538
1539   GNUNET_assert (NULL != active_task);
1540   GNUNET_assert (NULL != task);
1541   t = GNUNET_new (struct GNUNET_SCHEDULER_Task);
1542   t->callback = task;
1543   t->callback_cls = task_cls;
1544 #if DEBUG_FDS
1545   if (-1 != rfd)
1546   {
1547     int flags = fcntl (rfd, F_GETFD);
1548
1549     if ((flags == -1) && (errno == EBADF))
1550     {
1551       LOG (GNUNET_ERROR_TYPE_ERROR,
1552            "Got invalid file descriptor %d!\n",
1553            rfd);
1554       init_backtrace (t);
1555       GNUNET_assert (0);
1556     }
1557   }
1558   if (-1 != wfd)
1559   {
1560     int flags = fcntl (wfd, F_GETFD);
1561
1562     if (flags == -1 && errno == EBADF)
1563     {
1564       LOG (GNUNET_ERROR_TYPE_ERROR,
1565            "Got invalid file descriptor %d!\n",
1566            wfd);
1567       init_backtrace (t);
1568       GNUNET_assert (0);
1569     }
1570   }
1571 #endif
1572   t->read_fd = rfd;
1573   GNUNET_assert (wfd >= -1);
1574   t->write_fd = wfd;
1575 #if PROFILE_DELAYS
1576   t->start_time = GNUNET_TIME_absolute_get ();
1577 #endif
1578   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1579   t->priority = check_priority ((priority == GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority : priority);
1580   t->lifeness = current_lifeness;
1581   //GNUNET_CONTAINER_DLL_insert (pending_head,
1582   //                             pending_tail,
1583   //                             t);
1584   //fdi = GNUNET_new (struct GNUNET_SCHEDULER_FdInfo);
1585   //initFdInfo(fdi, t);
1586   //scheduler_driver->add(scheduler_driver->cls, t , fdi);
1587   //initFdInfo (&t->fdx, read_nh, write_nh, read_fh, write_fh)
1588   initFdInfo (t, read_nh, write_nh, read_fh, write_fh);
1589   // FIXME: call add for each fdi if t->fds is a list
1590   scheduler_driver->add(scheduler_driver->cls, t , fdi);
1591   
1592   max_priority_added = GNUNET_MAX (max_priority_added,
1593                                    t->priority);
1594   LOG (GNUNET_ERROR_TYPE_DEBUG,
1595        "Adding task %p\n",
1596        t);
1597   init_backtrace (t);
1598   return t;
1599 }
1600 #endif
1601
1602
1603 /**
1604  * Schedule a new task to be run with a specified delay or when the
1605  * specified file descriptor is ready for reading.  The delay can be
1606  * used as a timeout on the socket being ready.  The task will be
1607  * scheduled for execution once either the delay has expired or the
1608  * socket operation is ready.  It will be run with the DEFAULT priority.
1609  *
1610  * @param delay when should this operation time out?
1611  * @param rfd read file-descriptor
1612  * @param task main function of the task
1613  * @param task_cls closure of @a task
1614  * @return unique task identifier for the job
1615  *         only valid until @a task is started!
1616  */
1617 struct GNUNET_SCHEDULER_Task *
1618 GNUNET_SCHEDULER_add_read_net (struct GNUNET_TIME_Relative delay,
1619                                struct GNUNET_NETWORK_Handle *rfd,
1620                                GNUNET_SCHEDULER_TaskCallback task,
1621                                void *task_cls)
1622 {
1623   return GNUNET_SCHEDULER_add_read_net_with_priority (delay,
1624                   GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1625                   rfd, task, task_cls);
1626 }
1627
1628
1629 /**
1630  * Schedule a new task to be run with a specified priority and to be
1631  * run after the specified delay or when the specified file descriptor
1632  * is ready for reading.  The delay can be used as a timeout on the
1633  * socket being ready.  The task will be scheduled for execution once
1634  * either the delay has expired or the socket operation is ready.  It
1635  * will be run with the DEFAULT priority.
1636  *
1637  * @param delay when should this operation time out?
1638  * @param priority priority to use for the task
1639  * @param rfd read file-descriptor
1640  * @param task main function of the task
1641  * @param task_cls closure of @a task
1642  * @return unique task identifier for the job
1643  *         only valid until @a task is started!
1644  */
1645 struct GNUNET_SCHEDULER_Task *
1646 GNUNET_SCHEDULER_add_read_net_with_priority (struct GNUNET_TIME_Relative delay,
1647                enum GNUNET_SCHEDULER_Priority priority,
1648                struct GNUNET_NETWORK_Handle *rfd,
1649                GNUNET_SCHEDULER_TaskCallback task,
1650                                              void *task_cls)
1651 {
1652   return GNUNET_SCHEDULER_add_net_with_priority (delay, priority,
1653                                                  rfd,
1654                                                  GNUNET_YES,
1655                                                  GNUNET_NO,
1656                                                  task, task_cls);
1657 }
1658
1659
1660 /**
1661  * Schedule a new task to be run with a specified delay or when the
1662  * specified file descriptor is ready for writing.  The delay can be
1663  * used as a timeout on the socket being ready.  The task will be
1664  * scheduled for execution once either the delay has expired or the
1665  * socket operation is ready.  It will be run with the priority of
1666  * the calling task.
1667  *
1668  * @param delay when should this operation time out?
1669  * @param wfd write file-descriptor
1670  * @param task main function of the task
1671  * @param task_cls closure of @a task
1672  * @return unique task identifier for the job
1673  *         only valid until @a task is started!
1674  */
1675 struct GNUNET_SCHEDULER_Task *
1676 GNUNET_SCHEDULER_add_write_net (struct GNUNET_TIME_Relative delay,
1677                                 struct GNUNET_NETWORK_Handle *wfd,
1678                                 GNUNET_SCHEDULER_TaskCallback task,
1679                                 void *task_cls)
1680 {
1681   return GNUNET_SCHEDULER_add_net_with_priority (delay,
1682                                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1683                                                  wfd,
1684                                                  GNUNET_NO, GNUNET_YES,
1685                                                  task, task_cls);
1686 }
1687
1688 /**
1689  * Schedule a new task to be run with a specified delay or when the
1690  * specified file descriptor is ready.  The delay can be
1691  * used as a timeout on the socket being ready.  The task will be
1692  * scheduled for execution once either the delay has expired or the
1693  * socket operation is ready.
1694  *
1695  * @param delay when should this operation time out?
1696  * @param priority priority of the task
1697  * @param fd file-descriptor
1698  * @param on_read whether to poll the file-descriptor for readability
1699  * @param on_write whether to poll the file-descriptor for writability
1700  * @param task main function of the task
1701  * @param task_cls closure of task
1702  * @return unique task identifier for the job
1703  *         only valid until "task" is started!
1704  */
1705 struct GNUNET_SCHEDULER_Task *
1706 GNUNET_SCHEDULER_add_net_with_priority  (struct GNUNET_TIME_Relative delay,
1707                                          enum GNUNET_SCHEDULER_Priority priority,
1708                                          struct GNUNET_NETWORK_Handle *fd,
1709                                          int on_read,
1710                                          int on_write,
1711                                          GNUNET_SCHEDULER_TaskCallback task,
1712                                          void *task_cls)
1713 {
1714 #if MINGW
1715   struct GNUNET_NETWORK_FDSet *s;
1716   struct GNUNET_SCHEDULER_Task * ret;
1717
1718   GNUNET_assert (NULL != fd);
1719   s = GNUNET_NETWORK_fdset_create ();
1720   GNUNET_NETWORK_fdset_set (s, fd);
1721   ret = GNUNET_SCHEDULER_add_select (
1722       priority, delay,
1723       on_read  ? s : NULL,
1724       on_write ? s : NULL,
1725       task, task_cls);
1726   GNUNET_NETWORK_fdset_destroy (s);
1727   return ret;
1728 #else
1729   GNUNET_assert (on_read || on_write);
1730   GNUNET_assert (GNUNET_NETWORK_get_fd (fd) >= 0);
1731   return add_without_sets (delay, priority,
1732                            on_read  ? fd : NULL,
1733                            on_write ? fd : NULL,
1734                            NULL,
1735                            NULL,
1736                            task, task_cls);
1737 #endif
1738 }
1739
1740
1741 /**
1742  * Schedule a new task to be run with a specified delay or when the
1743  * specified file descriptor is ready for reading.  The delay can be
1744  * used as a timeout on the socket being ready.  The task will be
1745  * scheduled for execution once either the delay has expired or the
1746  * socket operation is ready. It will be run with the DEFAULT priority.
1747  *
1748  * @param delay when should this operation time out?
1749  * @param rfd read file-descriptor
1750  * @param task main function of the task
1751  * @param task_cls closure of @a task
1752  * @return unique task identifier for the job
1753  *         only valid until @a task is started!
1754  */
1755 struct GNUNET_SCHEDULER_Task *
1756 GNUNET_SCHEDULER_add_read_file (struct GNUNET_TIME_Relative delay,
1757                                 const struct GNUNET_DISK_FileHandle *rfd,
1758                                 GNUNET_SCHEDULER_TaskCallback task, void *task_cls)
1759 {
1760   return GNUNET_SCHEDULER_add_file_with_priority (
1761       delay, GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1762       rfd, GNUNET_YES, GNUNET_NO,
1763       task, task_cls);
1764 }
1765
1766
1767 /**
1768  * Schedule a new task to be run with a specified delay or when the
1769  * specified file descriptor is ready for writing.  The delay can be
1770  * used as a timeout on the socket being ready.  The task will be
1771  * scheduled for execution once either the delay has expired or the
1772  * socket operation is ready. It will be run with the DEFAULT priority.
1773  *
1774  * @param delay when should this operation time out?
1775  * @param wfd write file-descriptor
1776  * @param task main function of the task
1777  * @param task_cls closure of @a task
1778  * @return unique task identifier for the job
1779  *         only valid until @a task is started!
1780  */
1781 struct GNUNET_SCHEDULER_Task *
1782 GNUNET_SCHEDULER_add_write_file (struct GNUNET_TIME_Relative delay,
1783                                  const struct GNUNET_DISK_FileHandle *wfd,
1784                                  GNUNET_SCHEDULER_TaskCallback task, void *task_cls)
1785 {
1786   return GNUNET_SCHEDULER_add_file_with_priority (
1787       delay, GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1788       wfd, GNUNET_NO, GNUNET_YES,
1789       task, task_cls);
1790 }
1791
1792
1793 /**
1794  * Schedule a new task to be run with a specified delay or when the
1795  * specified file descriptor is ready.  The delay can be
1796  * used as a timeout on the socket being ready.  The task will be
1797  * scheduled for execution once either the delay has expired or the
1798  * socket operation is ready.
1799  *
1800  * @param delay when should this operation time out?
1801  * @param priority priority of the task
1802  * @param fd file-descriptor
1803  * @param on_read whether to poll the file-descriptor for readability
1804  * @param on_write whether to poll the file-descriptor for writability
1805  * @param task main function of the task
1806  * @param task_cls closure of @a task
1807  * @return unique task identifier for the job
1808  *         only valid until @a task is started!
1809  */
1810 struct GNUNET_SCHEDULER_Task *
1811 GNUNET_SCHEDULER_add_file_with_priority (struct GNUNET_TIME_Relative delay,
1812                                          enum GNUNET_SCHEDULER_Priority priority,
1813                                          const struct GNUNET_DISK_FileHandle *fd,
1814                                          int on_read, int on_write,
1815                                          GNUNET_SCHEDULER_TaskCallback task, void *task_cls)
1816 {
1817 #if MINGW
1818   struct GNUNET_NETWORK_FDSet *s;
1819   struct GNUNET_SCHEDULER_Task * ret;
1820
1821   GNUNET_assert (NULL != fd);
1822   s = GNUNET_NETWORK_fdset_create ();
1823   GNUNET_NETWORK_fdset_handle_set (s, fd);
1824   ret = GNUNET_SCHEDULER_add_select (
1825       priority, delay,
1826       on_read  ? s : NULL,
1827       on_write ? s : NULL,
1828       task, task_cls);
1829   GNUNET_NETWORK_fdset_destroy (s);
1830   return ret;
1831 #else
1832   GNUNET_assert (on_read || on_write);
1833   GNUNET_assert(fd->fd >= 0);
1834   return add_without_sets (delay, priority,
1835                            NULL,
1836                            NULL,
1837                            on_read ? fd : NULL,
1838                            on_write ? fd : NULL,
1839                            task, task_cls);
1840 #endif
1841 }
1842
1843
1844 /**
1845  * Schedule a new task to be run with a specified delay or when any of
1846  * the specified file descriptor sets is ready.  The delay can be used
1847  * as a timeout on the socket(s) being ready.  The task will be
1848  * scheduled for execution once either the delay has expired or any of
1849  * the socket operations is ready.  This is the most general
1850  * function of the "add" family.  Note that the "prerequisite_task"
1851  * must be satisfied in addition to any of the other conditions.  In
1852  * other words, the task will be started when
1853  * <code>
1854  * (prerequisite-run)
1855  * && (delay-ready
1856  *     || any-rs-ready
1857  *     || any-ws-ready) )
1858  * </code>
1859  *
1860  * @param prio how important is this task?
1861  * @param delay how long should we wait?
1862  * @param rs set of file descriptors we want to read (can be NULL)
1863  * @param ws set of file descriptors we want to write (can be NULL)
1864  * @param task main function of the task
1865  * @param task_cls closure of @a task
1866  * @return unique task identifier for the job
1867  *         only valid until @a task is started!
1868  */
1869 struct GNUNET_SCHEDULER_Task *
1870 GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio,
1871                              struct GNUNET_TIME_Relative delay,
1872                              const struct GNUNET_NETWORK_FDSet *rs,
1873                              const struct GNUNET_NETWORK_FDSet *ws,
1874                              GNUNET_SCHEDULER_TaskCallback task,
1875                              void *task_cls)
1876 {
1877   struct GNUNET_SCHEDULER_Task *t;
1878
1879   if ( (NULL == rs) &&
1880        (NULL == ws) )
1881     return GNUNET_SCHEDULER_add_delayed_with_priority (delay,
1882                                                        prio,
1883                                                        task,
1884                                                        task_cls);
1885   GNUNET_assert (NULL != active_task);
1886   GNUNET_assert (NULL != task);
1887   t = GNUNET_new (struct GNUNET_SCHEDULER_Task);
1888   t->callback = task;
1889   t->callback_cls = task_cls;
1890   t->read_fd = -1;
1891   t->write_fd = -1;
1892   if (NULL != rs)
1893   {
1894     t->read_set = GNUNET_NETWORK_fdset_create ();
1895     GNUNET_NETWORK_fdset_copy (t->read_set, rs);
1896   }
1897   if (NULL != ws)
1898   {
1899     t->write_set = GNUNET_NETWORK_fdset_create ();
1900     GNUNET_NETWORK_fdset_copy (t->write_set, ws);
1901   }
1902 #if PROFILE_DELAYS
1903   t->start_time = GNUNET_TIME_absolute_get ();
1904 #endif
1905   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1906   t->priority =
1907       check_priority ((prio ==
1908                        GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority :
1909                       prio);
1910   t->lifeness = current_lifeness;
1911   /*GNUNET_CONTAINER_DLL_insert (pending_head,
1912                                pending_tail,
1913                                t);*/
1914   fdi = GNUNET_new (struct GNUNET_SCHEDULER_FdInfo);
1915   initFdInfo(fdi, t);
1916   scheduler_driver->add(scheduler_driver->cls, t , fdi);
1917   max_priority_added = GNUNET_MAX (max_priority_added,
1918            t->priority);
1919   LOG (GNUNET_ERROR_TYPE_DEBUG,
1920        "Adding task %p\n",
1921        t);
1922   init_backtrace (t);
1923   return t;
1924 }
1925
1926
1927 /**
1928  * Function used by event-loop implementations to signal the scheduler
1929  * that a particular @a task is ready due to an event of type @a et.
1930  *
1931  * This function will then queue the task to notify the application
1932  * that the task is ready (with the respective priority).
1933  *
1934  * @param task the task that is ready, NULL for wake up calls
1935  * @param et information about why the task is ready
1936  */
1937 void
1938 GNUNET_SCHEDULER_task_ready (struct GNUNET_SCHEDULER_Task *task,
1939            enum GNUNET_SCHEDULER_EventType et)
1940 {
1941   enum GNUNET_SCHEDULER_Reason reason;
1942   struct GNUNET_TIME_Absolute now;
1943
1944   now = GNUNET_TIME_absolute_get ();
1945   reason = task->reason;
1946   if (now.abs_value_us >= task->timeout.abs_value_us)
1947     reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
1948   if ( (0 == (reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
1949        (0 != (GNUNET_SCHEDULER_ET_IN & et)) )
1950     reason |= GNUNET_SCHEDULER_REASON_READ_READY;
1951   if ( (0 == (reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) &&
1952        (0 != (GNUNET_SCHEDULER_ET_OUT & et)) )
1953     reason |= GNUNET_SCHEDULER_REASON_WRITE_READY;
1954   reason |= GNUNET_SCHEDULER_REASON_PREREQ_DONE;
1955   task->reason = reason;
1956   task->fds = &task->fdx;
1957   task->fdx.et = et;
1958   task->fds_len = 1;
1959   queue_ready_task (task);
1960 }
1961
1962
1963 /**
1964  * Function called by the driver to tell the scheduler to run some of
1965  * the tasks that are ready.  This function may return even though
1966  * there are tasks left to run just to give other tasks a chance as
1967  * well.  If we return #GNUNET_YES, the driver should call this
1968  * function again as soon as possible, while if we return #GNUNET_NO
1969  * it must block until the operating system has more work as the
1970  * scheduler has no more work to do right now.
1971  *
1972  * @param sh scheduler handle that was given to the `loop`
1973  * @return #GNUNET_OK if there are more tasks that are ready,
1974  *          and thus we would like to run more (yield to avoid
1975  *          blocking other activities for too long)
1976  *         #GNUNET_NO if we are done running tasks (yield to block)
1977  *         #GNUNET_SYSERR on error
1978  */
1979 int
1980 GNUNET_SCHEDULER_run_from_driver (struct GNUNET_SCHEDULER_Handle *sh)
1981 {
1982   enum GNUNET_SCHEDULER_Priority p;
1983   struct GNUNET_SCHEDULER_Task *pos;
1984   struct GNUNET_TIME_Absolute now;
1985
1986   /* check for tasks that reached the timeout! */
1987   now = GNUNET_TIME_absolute_get ();
1988   while (NULL != (pos = pending_timeout_head))
1989   {
1990     if (now.abs_value_us >= pos->timeout.abs_value_us)
1991       pos->reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
1992     if (0 == pos->reason)
1993       break;
1994     GNUNET_CONTAINER_DLL_remove (pending_timeout_head,
1995                                  pending_timeout_tail,
1996                                  pos);
1997     if (pending_timeout_last == pos)
1998       pending_timeout_last = NULL;
1999     queue_ready_task (pos);
2000   }
2001
2002   if (0 == ready_count)
2003     return GNUNET_NO;
2004
2005   /* find out which task priority level we are going to
2006      process this time */
2007   max_priority_added = GNUNET_SCHEDULER_PRIORITY_KEEP;
2008   GNUNET_assert (NULL == ready_head[GNUNET_SCHEDULER_PRIORITY_KEEP]);
2009   /* yes, p>0 is correct, 0 is "KEEP" which should
2010    * always be an empty queue (see assertion)! */
2011   for (p = GNUNET_SCHEDULER_PRIORITY_COUNT - 1; p > 0; p--)
2012   {
2013     pos = ready_head[p];
2014     if (NULL != pos)
2015       break;
2016   }
2017   GNUNET_assert (NULL != pos);        /* ready_count wrong? */
2018
2019   /* process all tasks at this priority level, then yield */
2020   while (NULL != (pos = ready_head[p]))
2021   {
2022     GNUNET_CONTAINER_DLL_remove (ready_head[p],
2023          ready_tail[p],
2024          pos);
2025     ready_count--;
2026     current_priority = pos->priority;
2027     current_lifeness = pos->lifeness;
2028     active_task = pos;
2029 #if PROFILE_DELAYS
2030     if (GNUNET_TIME_absolute_get_duration (pos->start_time).rel_value_us >
2031   DELAY_THRESHOLD.rel_value_us)
2032     {
2033       LOG (GNUNET_ERROR_TYPE_DEBUG,
2034      "Task %p took %s to be scheduled\n",
2035      pos,
2036      GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pos->start_time),
2037                GNUNET_YES));
2038     }
2039 #endif
2040     tc.reason = pos->reason;
2041     GNUNET_NETWORK_fdset_zero (sh->rs);
2042     GNUNET_NETWORK_fdset_zero (sh->ws);
2043     tc.fds_len = pos->fds_len;
2044     tc.fds = pos->fds;
2045     tc.read_ready = (NULL == pos->read_set) ? sh->rs : pos->read_set;
2046     if ( (-1 != pos->read_fd) &&
2047    (0 != (pos->reason & GNUNET_SCHEDULER_REASON_READ_READY)) )
2048       GNUNET_NETWORK_fdset_set_native (sh->rs,
2049                pos->read_fd);
2050     tc.write_ready = (NULL == pos->write_set) ? sh->ws : pos->write_set;
2051     if ((-1 != pos->write_fd) &&
2052   (0 != (pos->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)))
2053       GNUNET_NETWORK_fdset_set_native (sh->ws,
2054                pos->write_fd);
2055     LOG (GNUNET_ERROR_TYPE_DEBUG,
2056    "Running task: %p\n",
2057    pos);
2058     pos->callback (pos->callback_cls);
2059     active_task = NULL;
2060     dump_backtrace (pos);
2061     destroy_task (pos);
2062     tasks_run++;
2063   }
2064   if (0 == ready_count)
2065     return GNUNET_NO;
2066   return GNUNET_OK;
2067 }
2068
2069
2070 /**
2071  * Initialize and run scheduler.  This function will return when all
2072  * tasks have completed.  On systems with signals, receiving a SIGTERM
2073  * (and other similar signals) will cause #GNUNET_SCHEDULER_shutdown
2074  * to be run after the active task is complete.  As a result, SIGTERM
2075  * causes all shutdown tasks to be scheduled with reason
2076  * #GNUNET_SCHEDULER_REASON_SHUTDOWN.  (However, tasks added
2077  * afterwards will execute normally!).  Note that any particular
2078  * signal will only shut down one scheduler; applications should
2079  * always only create a single scheduler.
2080  *
2081  * @param driver drive to use for the event loop
2082  * @param task task to run first (and immediately)
2083  * @param task_cls closure of @a task
2084  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
2085  */
2086 int
2087 GNUNET_SCHEDULER_run_with_driver (const struct GNUNET_SCHEDULER_Driver *driver,
2088           GNUNET_SCHEDULER_TaskCallback task,
2089           void *task_cls)
2090 {
2091   int ret;
2092   struct GNUNET_SIGNAL_Context *shc_int;
2093   struct GNUNET_SIGNAL_Context *shc_term;
2094 #if (SIGTERM != GNUNET_TERM_SIG)
2095   struct GNUNET_SIGNAL_Context *shc_gterm;
2096 #endif
2097 #ifndef MINGW
2098   struct GNUNET_SIGNAL_Context *shc_quit;
2099   struct GNUNET_SIGNAL_Context *shc_hup;
2100   struct GNUNET_SIGNAL_Context *shc_pipe;
2101 #endif
2102   struct GNUNET_SCHEDULER_Task tsk;
2103   const struct GNUNET_DISK_FileHandle *pr;
2104   scheduler_driver = driver;
2105
2106   /* general set-up */
2107   GNUNET_assert (NULL == active_task);
2108   GNUNET_assert (NULL == shutdown_pipe_handle);
2109   shutdown_pipe_handle = GNUNET_DISK_pipe (GNUNET_NO,
2110                                            GNUNET_NO,
2111                                            GNUNET_NO,
2112                                            GNUNET_NO);
2113   GNUNET_assert (NULL != shutdown_pipe_handle);
2114   pr = GNUNET_DISK_pipe_handle (shutdown_pipe_handle,
2115                                 GNUNET_DISK_PIPE_END_READ);
2116   GNUNET_assert (NULL != pr);
2117   my_pid = getpid ();
2118
2119   /* install signal handlers */
2120   LOG (GNUNET_ERROR_TYPE_DEBUG,
2121        "Registering signal handlers\n");
2122   shc_int = GNUNET_SIGNAL_handler_install (SIGINT,
2123              &sighandler_shutdown);
2124   shc_term = GNUNET_SIGNAL_handler_install (SIGTERM,
2125               &sighandler_shutdown);
2126 #if (SIGTERM != GNUNET_TERM_SIG)
2127   shc_gterm = GNUNET_SIGNAL_handler_install (GNUNET_TERM_SIG,
2128                &sighandler_shutdown);
2129 #endif
2130 #ifndef MINGW
2131   shc_pipe = GNUNET_SIGNAL_handler_install (SIGPIPE,
2132               &sighandler_pipe);
2133   shc_quit = GNUNET_SIGNAL_handler_install (SIGQUIT,
2134               &sighandler_shutdown);
2135   shc_hup = GNUNET_SIGNAL_handler_install (SIGHUP,
2136              &sighandler_shutdown);
2137 #endif
2138
2139   /* Setup initial tasks */
2140   current_priority = GNUNET_SCHEDULER_PRIORITY_DEFAULT;
2141   current_lifeness = GNUNET_YES;
2142   memset (&tsk,
2143     0,
2144     sizeof (tsk));
2145   active_task = &tsk;
2146   tsk.sh = &sh;
2147   GNUNET_SCHEDULER_add_with_reason_and_priority (task,
2148                                                  task_cls,
2149                                                  GNUNET_SCHEDULER_REASON_STARTUP,
2150                                                  GNUNET_SCHEDULER_PRIORITY_DEFAULT);
2151   GNUNET_SCHEDULER_add_now_with_lifeness (GNUNET_NO,
2152                                           &GNUNET_OS_install_parent_control_handler,
2153                                           NULL);
2154   active_task = NULL;
2155   driver->set_wakeup (driver->cls,
2156           GNUNET_TIME_absolute_get ());
2157
2158   /* begin main event loop */
2159   sh.rs = GNUNET_NETWORK_fdset_create ();
2160   sh.ws = GNUNET_NETWORK_fdset_create ();
2161   GNUNET_NETWORK_fdset_handle_set (rs, pr);
2162   sh.driver = driver;
2163   ret = driver->loop (driver->cls,
2164           &sh);
2165   GNUNET_NETWORK_fdset_destroy (sh.rs);
2166   GNUNET_NETWORK_fdset_destroy (sh.ws);
2167
2168   /* uninstall signal handlers */
2169   GNUNET_SIGNAL_handler_uninstall (shc_int);
2170   GNUNET_SIGNAL_handler_uninstall (shc_term);
2171 #if (SIGTERM != GNUNET_TERM_SIG)
2172   GNUNET_SIGNAL_handler_uninstall (shc_gterm);
2173 #endif
2174 #ifndef MINGW
2175   GNUNET_SIGNAL_handler_uninstall (shc_pipe);
2176   GNUNET_SIGNAL_handler_uninstall (shc_quit);
2177   GNUNET_SIGNAL_handler_uninstall (shc_hup);
2178 #endif
2179   GNUNET_DISK_pipe_close (shutdown_pipe_handle);
2180   shutdown_pipe_handle = NULL;
2181   return ret;
2182 }
2183
2184 int
2185 select_add(void *cls,
2186  struct GNUNET_SCHEDULER_Task *task,
2187  struct GNUNET_SCHEDULER_FdInfo *fdi){
2188
2189   GNUNET_CONTAINER_DLL_insert (pending_head,
2190                                pending_tail,
2191                                task);
2192
2193 }
2194
2195 int
2196 select_del(void *cls,
2197  struct GNUNET_SCHEDULER_Task *task,
2198  struct GNUNET_SCHEDULER_FdInfo *fdi){
2199
2200   GNUNET_CONTAINER_DLL_remove (pending_head,
2201                                pending_tail,
2202                                task);
2203
2204 }
2205
2206
2207 int
2208 select_loop(void *cls,
2209         struct GNUNET_SCHEDULER_Handle *sh){
2210
2211   while_live(sh-rs, sh->ws);
2212
2213 }
2214
2215 void
2216 select_set_wakeup(void *cls,
2217                    struct GNUNET_TIME_Absolute dt){
2218
2219
2220
2221 }
2222
2223
2224 /**
2225  * Obtain the driver for using select() as the event loop.
2226  *
2227  * @return NULL on error
2228  */
2229 const struct GNUNET_SCHEDULER_Driver *
2230 GNUNET_SCHEDULER_driver_select ()
2231 {
2232
2233   GNUNET_SCHEDULER_Driver *select_driver;
2234
2235   select_driver = GNUNET_new (struct GNUNET_SCHEDULER_Driver);
2236
2237   select_driver->loop = &select_loop;
2238   select_driver->add = &select_add;
2239   select_driver->del = &select_del;
2240   select_driver->set_wakeup = &select_set_wakeup;
2241
2242
2243   return select_driver;
2244 }
2245
2246
2247 /* end of scheduler.c */