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