9b49df79a3d007a761c0acfe44cfe3802b094b90
[oweals/gnunet.git] / src / util / scheduler.c
1 /*
2       This file is part of GNUnet
3       (C) 2009, 2011 Christian Grothoff (and other contributing authors)
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 2, 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., 59 Temple Place - Suite 330,
18       Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * @file util/scheduler.c
23  * @brief schedule computations using continuation passing style
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet_common.h"
28 #include "gnunet_os_lib.h"
29 #include "gnunet_scheduler_lib.h"
30 #include "gnunet_signal_lib.h"
31 #include "gnunet_time_lib.h"
32 #include "disk.h"
33
34 #define LOG(kind,...) GNUNET_log_from (kind, "util-scheduler", __VA_ARGS__)
35
36 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-scheduler", syscall)
37
38
39 #if HAVE_EXECINFO_H
40 #include "execinfo.h"
41
42 /**
43  * Use lsof to generate file descriptor reports on select error?
44  * (turn off for stable releases).
45  */
46 #define USE_LSOF GNUNET_NO
47
48 /**
49  * Obtain trace information for all scheduler calls that schedule tasks.
50  */
51 #define EXECINFO GNUNET_NO
52
53 /**
54  * Check each file descriptor before adding
55  */
56 #define DEBUG_FDS GNUNET_NO
57
58 /**
59  * Depth of the traces collected via EXECINFO.
60  */
61 #define MAX_TRACE_DEPTH 50
62 #endif
63
64 /**
65  * Should we figure out which tasks are delayed for a while
66  * before they are run? (Consider using in combination with EXECINFO).
67  */
68 #define PROFILE_DELAYS GNUNET_NO
69
70 /**
71  * Task that were in the queue for longer than this are reported if
72  * PROFILE_DELAYS is active.
73  */
74 #define DELAY_THRESHOLD GNUNET_TIME_UNIT_SECONDS
75
76
77 /**
78  * Linked list of pending tasks.
79  */
80 struct Task
81 {
82   /**
83    * This is a linked list.
84    */
85   struct Task *next;
86
87   /**
88    * Function to run when ready.
89    */
90   GNUNET_SCHEDULER_Task callback;
91
92   /**
93    * Closure for the callback.
94    */
95   void *callback_cls;
96
97   /**
98    * Set of file descriptors this task is waiting
99    * for for reading.  Once ready, this is updated
100    * to reflect the set of file descriptors ready
101    * for operation.
102    */
103   struct GNUNET_NETWORK_FDSet *read_set;
104
105   /**
106    * Set of file descriptors this task is waiting for for writing.
107    * Once ready, this is updated to reflect the set of file
108    * descriptors ready for operation.
109    */
110   struct GNUNET_NETWORK_FDSet *write_set;
111
112   /**
113    * Unique task identifier.
114    */
115   GNUNET_SCHEDULER_TaskIdentifier id;
116
117   /**
118    * Absolute timeout value for the task, or
119    * GNUNET_TIME_UNIT_FOREVER_ABS for "no timeout".
120    */
121   struct GNUNET_TIME_Absolute timeout;
122
123 #if PROFILE_DELAYS
124   /**
125    * When was the task scheduled?
126    */
127   struct GNUNET_TIME_Absolute start_time;
128 #endif
129
130   /**
131    * Why is the task ready?  Set after task is added to ready queue.
132    * Initially set to zero.  All reasons that have already been
133    * satisfied (i.e.  read or write ready) will be set over time.
134    */
135   enum GNUNET_SCHEDULER_Reason reason;
136
137   /**
138    * Task priority.
139    */
140   enum GNUNET_SCHEDULER_Priority priority;
141
142   /**
143    * Set if we only wait for reading from a single FD, otherwise -1.
144    */
145   int read_fd;
146
147   /**
148    * Set if we only wait for writing to a single FD, otherwise -1.
149    */
150   int write_fd;
151
152   /**
153    * Should the existence of this task in the queue be counted as
154    * reason to not shutdown the scheduler?
155    */
156   int lifeness;
157
158 #if EXECINFO
159   /**
160    * Array of strings which make up a backtrace from the point when this
161    * task was scheduled (essentially, who scheduled the task?)
162    */
163   char **backtrace_strings;
164
165   /**
166    * Size of the backtrace_strings array
167    */
168   int num_backtrace_strings;
169 #endif
170
171
172 };
173
174
175 /**
176  * List of tasks waiting for an event.
177  */
178 static struct Task *pending;
179
180 /**
181  * List of tasks waiting ONLY for a timeout event.
182  * Sorted by timeout (earliest first).  Used so that
183  * we do not traverse the list of these tasks when
184  * building select sets (we just look at the head
185  * to determine the respective timeout ONCE).
186  */
187 static struct Task *pending_timeout;
188
189 /**
190  * Last inserted task waiting ONLY for a timeout event.
191  * Used to (heuristically) speed up insertion.
192  */
193 static struct Task *pending_timeout_last;
194
195 /**
196  * ID of the task that is running right now.
197  */
198 static struct Task *active_task;
199
200 /**
201  * List of tasks ready to run right now,
202  * grouped by importance.
203  */
204 static struct Task *ready[GNUNET_SCHEDULER_PRIORITY_COUNT];
205
206 /**
207  * Identity of the last task queued.  Incremented for each task to
208  * generate a unique task ID (it is virtually impossible to start
209  * more than 2^64 tasks during the lifetime of a process).
210  */
211 static GNUNET_SCHEDULER_TaskIdentifier last_id;
212
213 /**
214  * Number of tasks on the ready list.
215  */
216 static unsigned int ready_count;
217
218 /**
219  * How many tasks have we run so far?
220  */
221 static unsigned long long tasks_run;
222
223 /**
224  * Priority of the task running right now.  Only
225  * valid while a task is running.
226  */
227 static enum GNUNET_SCHEDULER_Priority current_priority;
228
229 /**
230  * Priority of the highest task added in the current select
231  * iteration.
232  */
233 static enum GNUNET_SCHEDULER_Priority max_priority_added;
234
235 /**
236  * Value of the 'lifeness' flag for the current task.
237  */
238 static int current_lifeness;
239
240 /**
241  * Function to use as a select() in the scheduler.
242  * If NULL, we use GNUNET_NETWORK_socket_select ().
243  */
244 static GNUNET_SCHEDULER_select scheduler_select;
245
246 /**
247  * Closure for 'scheduler_select'.
248  */
249 static void *scheduler_select_cls;
250
251 /**
252  * Sets the select function to use in the scheduler (scheduler_select).
253  *
254  * @param new_select new select function to use
255  * @param new_select_cls closure for 'new_select'
256  * @return previously used select function, NULL for default
257  */
258 void
259 GNUNET_SCHEDULER_set_select (GNUNET_SCHEDULER_select new_select,
260                              void *new_select_cls)
261 {
262   scheduler_select = new_select;
263   scheduler_select_cls = new_select_cls;
264 }
265
266
267 /**
268  * Check that the given priority is legal (and return it).
269  *
270  * @param p priority value to check
271  * @return p on success, 0 on error
272  */
273 static enum GNUNET_SCHEDULER_Priority
274 check_priority (enum GNUNET_SCHEDULER_Priority p)
275 {
276   if ((p >= 0) && (p < GNUNET_SCHEDULER_PRIORITY_COUNT))
277     return p;
278   GNUNET_assert (0);
279   return 0;                     /* make compiler happy */
280 }
281
282
283 /**
284  * Update all sets and timeout for select.
285  *
286  * @param rs read-set, set to all FDs we would like to read (updated)
287  * @param ws write-set, set to all FDs we would like to write (updated)
288  * @param timeout next timeout (updated)
289  */
290 static void
291 update_sets (struct GNUNET_NETWORK_FDSet *rs, struct GNUNET_NETWORK_FDSet *ws,
292              struct GNUNET_TIME_Relative *timeout)
293 {
294   struct Task *pos;
295   struct GNUNET_TIME_Absolute now;
296   struct GNUNET_TIME_Relative to;
297
298   now = GNUNET_TIME_absolute_get ();
299   pos = pending_timeout;
300   if (pos != NULL)
301   {
302     to = GNUNET_TIME_absolute_get_difference (now, pos->timeout);
303     if (timeout->rel_value > to.rel_value)
304       *timeout = to;
305     if (pos->reason != 0)
306       *timeout = GNUNET_TIME_UNIT_ZERO;
307   }
308   pos = pending;
309   while (pos != NULL)
310   {
311     if (pos->timeout.abs_value != GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
312     {
313       to = GNUNET_TIME_absolute_get_difference (now, pos->timeout);
314       if (timeout->rel_value > to.rel_value)
315         *timeout = to;
316     }
317     if (pos->read_fd != -1)
318       GNUNET_NETWORK_fdset_set_native (rs, pos->read_fd);
319     if (pos->write_fd != -1)
320       GNUNET_NETWORK_fdset_set_native (ws, pos->write_fd);
321     if (pos->read_set != NULL)
322       GNUNET_NETWORK_fdset_add (rs, pos->read_set);
323     if (pos->write_set != NULL)
324       GNUNET_NETWORK_fdset_add (ws, pos->write_set);
325     if (pos->reason != 0)
326       *timeout = GNUNET_TIME_UNIT_ZERO;
327     pos = pos->next;
328   }
329 }
330
331
332 /**
333  * Check if the ready set overlaps with the set we want to have ready.
334  * If so, update the want set (set all FDs that are ready).  If not,
335  * return GNUNET_NO.
336  *
337  * @param ready set that is ready
338  * @param want set that we want to be ready
339  * @return GNUNET_YES if there was some overlap
340  */
341 static int
342 set_overlaps (const struct GNUNET_NETWORK_FDSet *ready,
343               struct GNUNET_NETWORK_FDSet *want)
344 {
345   if ((NULL == want) || (NULL == ready))
346     return GNUNET_NO;
347   if (GNUNET_NETWORK_fdset_overlap (ready, want))
348   {
349     /* copy all over (yes, there maybe unrelated bits,
350      * but this should not hurt well-written clients) */
351     GNUNET_NETWORK_fdset_copy (want, ready);
352     return GNUNET_YES;
353   }
354   return GNUNET_NO;
355 }
356
357
358 /**
359  * Check if the given task is eligible to run now.
360  * Also set the reason why it is eligible.
361  *
362  * @param task task to check if it is ready
363  * @param now the current time
364  * @param rs set of FDs ready for reading
365  * @param ws set of FDs ready for writing
366  * @return GNUNET_YES if we can run it, GNUNET_NO if not.
367  */
368 static int
369 is_ready (struct Task *task, struct GNUNET_TIME_Absolute now,
370           const struct GNUNET_NETWORK_FDSet *rs,
371           const struct GNUNET_NETWORK_FDSet *ws)
372 {
373   enum GNUNET_SCHEDULER_Reason reason;
374
375   reason = task->reason;
376   if (now.abs_value >= task->timeout.abs_value)
377     reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
378   if ((0 == (reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
379       (((task->read_fd != -1) &&
380         (GNUNET_YES == GNUNET_NETWORK_fdset_test_native (rs, task->read_fd))) ||
381        (set_overlaps (rs, task->read_set))))
382     reason |= GNUNET_SCHEDULER_REASON_READ_READY;
383   if ((0 == (reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) &&
384       (((task->write_fd != -1) &&
385         (GNUNET_YES == GNUNET_NETWORK_fdset_test_native (ws, task->write_fd)))
386        || (set_overlaps (ws, task->write_set))))
387     reason |= GNUNET_SCHEDULER_REASON_WRITE_READY;
388   if (reason == 0)
389     return GNUNET_NO;           /* not ready */
390   reason |= GNUNET_SCHEDULER_REASON_PREREQ_DONE;  
391   task->reason = reason;
392   return GNUNET_YES;
393 }
394
395
396 /**
397  * Put a task that is ready for execution into the ready queue.
398  *
399  * @param task task ready for execution
400  */
401 static void
402 queue_ready_task (struct Task *task)
403 {
404   enum GNUNET_SCHEDULER_Priority p = task->priority;
405
406   if (0 != (task->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
407     p = GNUNET_SCHEDULER_PRIORITY_SHUTDOWN;
408   task->next = ready[check_priority (p)];
409   ready[check_priority (p)] = task;
410   ready_count++;
411 }
412
413
414 /**
415  * Check which tasks are ready and move them
416  * to the respective ready queue.
417  *
418  * @param rs FDs ready for reading
419  * @param ws FDs ready for writing
420  */
421 static void
422 check_ready (const struct GNUNET_NETWORK_FDSet *rs,
423              const struct GNUNET_NETWORK_FDSet *ws)
424 {
425   struct Task *pos;
426   struct Task *prev;
427   struct Task *next;
428   struct GNUNET_TIME_Absolute now;
429
430   now = GNUNET_TIME_absolute_get ();
431   prev = NULL;
432   pos = pending_timeout;
433   while (pos != NULL)
434   {
435     next = pos->next;
436     if (now.abs_value >= pos->timeout.abs_value)
437       pos->reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
438     if (0 == pos->reason)
439       break;
440     pending_timeout = next;
441     if (pending_timeout_last == pos)
442       pending_timeout_last = NULL;
443     queue_ready_task (pos);
444     pos = next;
445   }
446   pos = pending;
447   while (pos != NULL)
448   {
449     LOG (GNUNET_ERROR_TYPE_DEBUG, 
450          "Checking readiness of task: %llu / %p\n",
451          pos->id, pos->callback_cls);
452     next = pos->next;
453     if (GNUNET_YES == is_ready (pos, now, rs, ws))
454     {
455       if (prev == NULL)
456         pending = next;
457       else
458         prev->next = next;
459       queue_ready_task (pos);
460       pos = next;
461       continue;
462     }
463     prev = pos;
464     pos = next;
465   }
466 }
467
468
469 /**
470  * Request the shutdown of a scheduler.  Marks all currently
471  * pending tasks as ready because of shutdown.  This will
472  * cause all tasks to run (as soon as possible, respecting
473  * priorities and prerequisite tasks).  Note that tasks
474  * scheduled AFTER this call may still be delayed arbitrarily.
475  */
476 void
477 GNUNET_SCHEDULER_shutdown ()
478 {
479   struct Task *pos;
480   int i;
481
482   pos = pending_timeout;
483   while (pos != NULL)
484   {
485     pos->reason |= GNUNET_SCHEDULER_REASON_SHUTDOWN;
486     /* we don't move the task into the ready queue yet; check_ready
487      * will do that later, possibly adding additional
488      * readiness-factors */
489     pos = pos->next;
490   }
491   pos = pending;
492   while (pos != NULL)
493   {
494     pos->reason |= GNUNET_SCHEDULER_REASON_SHUTDOWN;
495     /* we don't move the task into the ready queue yet; check_ready
496      * will do that later, possibly adding additional
497      * readiness-factors */
498     pos = pos->next;
499   }
500   for (i = 0; i < GNUNET_SCHEDULER_PRIORITY_COUNT; i++)
501   {
502     pos = ready[i];
503     while (pos != NULL)
504     {
505       pos->reason |= GNUNET_SCHEDULER_REASON_SHUTDOWN;
506       /* we don't move the task into the ready queue yet; check_ready
507        * will do that later, possibly adding additional
508        * readiness-factors */
509       pos = pos->next;
510     }
511   }
512 }
513
514
515 /**
516  * Destroy a task (release associated resources)
517  *
518  * @param t task to destroy
519  */
520 static void
521 destroy_task (struct Task *t)
522 {
523   if (NULL != t->read_set)
524     GNUNET_NETWORK_fdset_destroy (t->read_set);
525   if (NULL != t->write_set)
526     GNUNET_NETWORK_fdset_destroy (t->write_set);
527 #if EXECINFO
528   GNUNET_free (t->backtrace_strings);
529 #endif
530   GNUNET_free (t);
531 }
532
533
534 /**
535  * Run at least one task in the highest-priority queue that is not
536  * empty.  Keep running tasks until we are either no longer running
537  * "URGENT" tasks or until we have at least one "pending" task (which
538  * may become ready, hence we should select on it).  Naturally, if
539  * there are no more ready tasks, we also return.
540  *
541  * @param rs FDs ready for reading
542  * @param ws FDs ready for writing
543  */
544 static void
545 run_ready (struct GNUNET_NETWORK_FDSet *rs, struct GNUNET_NETWORK_FDSet *ws)
546 {
547   enum GNUNET_SCHEDULER_Priority p;
548   struct Task *pos;
549   struct GNUNET_SCHEDULER_TaskContext tc;
550
551   max_priority_added = GNUNET_SCHEDULER_PRIORITY_KEEP;
552   do
553   {
554     if (ready_count == 0)
555       return;
556     GNUNET_assert (ready[GNUNET_SCHEDULER_PRIORITY_KEEP] == NULL);
557     /* yes, p>0 is correct, 0 is "KEEP" which should
558      * always be an empty queue (see assertion)! */
559     for (p = GNUNET_SCHEDULER_PRIORITY_COUNT - 1; p > 0; p--)
560     {
561       pos = ready[p];
562       if (pos != NULL)
563         break;
564     }
565     GNUNET_assert (pos != NULL);        /* ready_count wrong? */
566     ready[p] = pos->next;
567     ready_count--;
568     current_priority = pos->priority;
569     current_lifeness = pos->lifeness;
570     active_task = pos;
571 #if PROFILE_DELAYS
572     if (GNUNET_TIME_absolute_get_duration (pos->start_time).rel_value >
573         DELAY_THRESHOLD.rel_value)
574     {
575       LOG (GNUNET_ERROR_TYPE_DEBUG, 
576            "Task %llu took %s to be scheduled\n",
577            (unsigned long long) pos->id,
578            GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pos->start_time), GNUNET_YES));
579     }
580 #endif
581     tc.reason = pos->reason;
582     tc.read_ready = (pos->read_set == NULL) ? rs : pos->read_set;
583     if ((pos->read_fd != -1) &&
584         (0 != (pos->reason & GNUNET_SCHEDULER_REASON_READ_READY)))
585       GNUNET_NETWORK_fdset_set_native (rs, pos->read_fd);
586     tc.write_ready = (pos->write_set == NULL) ? ws : pos->write_set;
587     if ((pos->write_fd != -1) &&
588         (0 != (pos->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)))
589       GNUNET_NETWORK_fdset_set_native (ws, pos->write_fd);
590     if (((tc.reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0) &&
591         (pos->write_fd != -1) &&
592         (!GNUNET_NETWORK_fdset_test_native (ws, pos->write_fd)))
593       GNUNET_abort ();          // added to ready in previous select loop!
594     LOG (GNUNET_ERROR_TYPE_DEBUG, 
595          "Running task: %llu / %p\n", pos->id,
596          pos->callback_cls);
597     pos->callback (pos->callback_cls, &tc);
598 #if EXECINFO
599     int i;
600
601     for (i = 0; i < pos->num_backtrace_strings; i++)
602       LOG (GNUNET_ERROR_TYPE_ERROR, "Task %llu trace %d: %s\n", pos->id, i,
603            pos->backtrace_strings[i]);
604 #endif
605     active_task = NULL;
606     destroy_task (pos);
607     tasks_run++;
608   }
609   while ((pending == NULL) || (p >= max_priority_added));
610 }
611
612 /**
613  * Pipe used to communicate shutdown via signal.
614  */
615 static struct GNUNET_DISK_PipeHandle *shutdown_pipe_handle;
616
617 /**
618  * Process ID of this process at the time we installed the various
619  * signal handlers.
620  */
621 static pid_t my_pid;
622
623 /**
624  * Signal handler called for SIGPIPE.
625  */
626 #ifndef MINGW
627 static void
628 sighandler_pipe ()
629 {
630   return;
631 }
632 #endif
633 /**
634  * Signal handler called for signals that should cause us to shutdown.
635  */
636 static void
637 sighandler_shutdown ()
638 {
639   static char c;
640   int old_errno = errno;        /* backup errno */
641
642   if (getpid () != my_pid)
643     exit (1);                   /* we have fork'ed since the signal handler was created,
644                                  * ignore the signal, see https://gnunet.org/vfork discussion */
645   LOG (GNUNET_ERROR_TYPE_DEBUG,
646        "Got signal %d from parent, writing to shutdown pipe\n");
647   GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
648                           (shutdown_pipe_handle, GNUNET_DISK_PIPE_END_WRITE),
649                           &c, sizeof (c));
650   errno = old_errno;
651 }
652
653
654 /**
655  * Check if the system is still life. Trigger shutdown if we
656  * have tasks, but none of them give us lifeness.
657  *
658  * @return GNUNET_OK to continue the main loop,
659  *         GNUNET_NO to exit
660  */
661 static int
662 check_lifeness ()
663 {
664   struct Task *t;
665
666   if (ready_count > 0)
667     return GNUNET_OK;
668   for (t = pending; NULL != t; t = t->next)
669     if (t->lifeness == GNUNET_YES)
670       return GNUNET_OK;
671   for (t = pending_timeout; NULL != t; t = t->next)
672     if (t->lifeness == GNUNET_YES)
673       return GNUNET_OK;
674   if ((NULL != pending) || (NULL != pending_timeout))
675   {
676     GNUNET_SCHEDULER_shutdown ();
677     return GNUNET_OK;
678   }
679   return GNUNET_NO;
680 }
681
682
683 /**
684  * Initialize and run scheduler.  This function will return when all
685  * tasks have completed.  On systems with signals, receiving a SIGTERM
686  * (and other similar signals) will cause "GNUNET_SCHEDULER_shutdown"
687  * to be run after the active task is complete.  As a result, SIGTERM
688  * causes all active tasks to be scheduled with reason
689  * "GNUNET_SCHEDULER_REASON_SHUTDOWN".  (However, tasks added
690  * afterwards will execute normally!). Note that any particular signal
691  * will only shut down one scheduler; applications should always only
692  * create a single scheduler.
693  *
694  * @param task task to run immediately
695  * @param task_cls closure of task
696  */
697 void
698 GNUNET_SCHEDULER_run (GNUNET_SCHEDULER_Task task, void *task_cls)
699 {
700   struct GNUNET_NETWORK_FDSet *rs;
701   struct GNUNET_NETWORK_FDSet *ws;
702   struct GNUNET_TIME_Relative timeout;
703   int ret;
704   struct GNUNET_SIGNAL_Context *shc_int;
705   struct GNUNET_SIGNAL_Context *shc_term;
706
707 #ifndef MINGW
708   struct GNUNET_SIGNAL_Context *shc_quit;
709   struct GNUNET_SIGNAL_Context *shc_hup;
710   struct GNUNET_SIGNAL_Context *shc_pipe;
711 #endif
712   unsigned long long last_tr;
713   unsigned int busy_wait_warning;
714   const struct GNUNET_DISK_FileHandle *pr;
715   char c;
716
717   GNUNET_assert (active_task == NULL);
718   rs = GNUNET_NETWORK_fdset_create ();
719   ws = GNUNET_NETWORK_fdset_create ();
720   GNUNET_assert (shutdown_pipe_handle == NULL);
721   shutdown_pipe_handle = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO);
722   GNUNET_assert (shutdown_pipe_handle != NULL);
723   pr = GNUNET_DISK_pipe_handle (shutdown_pipe_handle,
724                                 GNUNET_DISK_PIPE_END_READ);
725   GNUNET_assert (pr != NULL);
726   my_pid = getpid ();
727   LOG (GNUNET_ERROR_TYPE_DEBUG, "Registering signal handlers\n");
728   shc_int = GNUNET_SIGNAL_handler_install (SIGINT, &sighandler_shutdown);
729   shc_term = GNUNET_SIGNAL_handler_install (SIGTERM, &sighandler_shutdown);
730 #ifndef MINGW
731   shc_pipe = GNUNET_SIGNAL_handler_install (SIGPIPE, &sighandler_pipe);
732   shc_quit = GNUNET_SIGNAL_handler_install (SIGQUIT, &sighandler_shutdown);
733   shc_hup = GNUNET_SIGNAL_handler_install (SIGHUP, &sighandler_shutdown);
734 #endif
735   current_priority = GNUNET_SCHEDULER_PRIORITY_DEFAULT;
736   current_lifeness = GNUNET_YES;
737   GNUNET_SCHEDULER_add_continuation (task, task_cls,
738                                      GNUNET_SCHEDULER_REASON_STARTUP);
739   active_task = (void *) (long) -1;     /* force passing of sanity check */
740   GNUNET_SCHEDULER_add_now_with_lifeness (GNUNET_NO,
741                                           &GNUNET_OS_install_parent_control_handler,
742                                           NULL);
743   active_task = NULL;
744   last_tr = 0;
745   busy_wait_warning = 0;
746   while (GNUNET_OK == check_lifeness ())
747   {
748     GNUNET_NETWORK_fdset_zero (rs);
749     GNUNET_NETWORK_fdset_zero (ws);
750     timeout = GNUNET_TIME_UNIT_FOREVER_REL;
751     update_sets (rs, ws, &timeout);
752     GNUNET_NETWORK_fdset_handle_set (rs, pr);
753     if (ready_count > 0)
754     {
755       /* no blocking, more work already ready! */
756       timeout = GNUNET_TIME_UNIT_ZERO;
757     }
758     if (NULL == scheduler_select)
759       ret = GNUNET_NETWORK_socket_select (rs, ws, NULL, timeout);
760     else
761       ret = scheduler_select (scheduler_select_cls, rs, ws, NULL, timeout);
762     if (ret == GNUNET_SYSERR)
763     {
764       if (errno == EINTR)
765         continue;
766
767       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "select");
768 #ifndef MINGW
769 #if USE_LSOF
770       char lsof[512];
771
772       snprintf (lsof, sizeof (lsof), "lsof -p %d", getpid ());
773       (void) close (1);
774       (void) dup2 (2, 1);
775       if (0 != system (lsof))
776         LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "system");
777 #endif
778 #endif
779       GNUNET_abort ();
780       break;
781     }
782     if ((ret == 0) && (timeout.rel_value == 0) && (busy_wait_warning > 16))
783     {
784       LOG (GNUNET_ERROR_TYPE_WARNING, _("Looks like we're busy waiting...\n"));
785       sleep (1);                /* mitigate */
786     }
787     check_ready (rs, ws);
788     run_ready (rs, ws);
789     if (GNUNET_NETWORK_fdset_handle_isset (rs, pr))
790     {
791       /* consume the signal */
792       GNUNET_DISK_file_read (pr, &c, sizeof (c));
793       /* mark all active tasks as ready due to shutdown */
794       GNUNET_SCHEDULER_shutdown ();
795     }
796     if (last_tr == tasks_run)
797     {
798       busy_wait_warning++;
799     }
800     else
801     {
802       last_tr = tasks_run;
803       busy_wait_warning = 0;
804     }
805   }
806   GNUNET_SIGNAL_handler_uninstall (shc_int);
807   GNUNET_SIGNAL_handler_uninstall (shc_term);
808 #ifndef MINGW
809   GNUNET_SIGNAL_handler_uninstall (shc_pipe);
810   GNUNET_SIGNAL_handler_uninstall (shc_quit);
811   GNUNET_SIGNAL_handler_uninstall (shc_hup);
812 #endif
813   GNUNET_DISK_pipe_close (shutdown_pipe_handle);
814   shutdown_pipe_handle = NULL;
815   GNUNET_NETWORK_fdset_destroy (rs);
816   GNUNET_NETWORK_fdset_destroy (ws);
817 }
818
819
820 /**
821  * Obtain the reason code for why the current task was
822  * started.  Will return the same value as
823  * the GNUNET_SCHEDULER_TaskContext's reason field.
824  *
825  * @return reason(s) why the current task is run
826  */
827 enum GNUNET_SCHEDULER_Reason
828 GNUNET_SCHEDULER_get_reason ()
829 {
830   GNUNET_assert (active_task != NULL);
831   return active_task->reason;
832 }
833
834
835 /**
836  * Get information about the current load of this scheduler.  Use this
837  * function to determine if an elective task should be added or simply
838  * dropped (if the decision should be made based on the number of
839  * tasks ready to run).
840  *
841  * @param p priority level to look at
842  * @return number of tasks pending right now
843  */
844 unsigned int
845 GNUNET_SCHEDULER_get_load (enum GNUNET_SCHEDULER_Priority p)
846 {
847   struct Task *pos;
848   unsigned int ret;
849
850   GNUNET_assert (active_task != NULL);
851   if (p == GNUNET_SCHEDULER_PRIORITY_COUNT)
852     return ready_count;
853   if (p == GNUNET_SCHEDULER_PRIORITY_KEEP)
854     p = current_priority;
855   ret = 0;
856   pos = ready[check_priority (p)];
857   while (pos != NULL)
858   {
859     pos = pos->next;
860     ret++;
861   }
862   return ret;
863 }
864
865
866 /**
867  * Cancel the task with the specified identifier.
868  * The task must not yet have run.
869  *
870  * @param task id of the task to cancel
871  * @return original closure of the task
872  */
873 void *
874 GNUNET_SCHEDULER_cancel (GNUNET_SCHEDULER_TaskIdentifier task)
875 {
876   struct Task *t;
877   struct Task *prev;
878   enum GNUNET_SCHEDULER_Priority p;
879   int to;
880   void *ret;
881
882   GNUNET_assert (active_task != NULL);
883   to = 0;
884   prev = NULL;
885   t = pending;
886   while (t != NULL)
887   {
888     if (t->id == task)
889       break;
890     prev = t;
891     t = t->next;
892   }
893   if (t == NULL)
894   {
895     prev = NULL;
896     to = 1;
897     t = pending_timeout;
898     while (t != NULL)
899     {
900       if (t->id == task)
901         break;
902       prev = t;
903       t = t->next;
904     }
905     if (pending_timeout_last == t)
906       pending_timeout_last = NULL;
907   }
908   p = 0;
909   while (t == NULL)
910   {
911     p++;
912     if (p >= GNUNET_SCHEDULER_PRIORITY_COUNT)
913     {
914       LOG (GNUNET_ERROR_TYPE_ERROR, _("Attempt to cancel dead task %llu!\n"),
915            (unsigned long long) task);
916       GNUNET_assert (0);
917     }
918     prev = NULL;
919     t = ready[p];
920     while (t != NULL)
921     {
922       if (t->id == task)
923       {
924         ready_count--;
925         break;
926       }
927       prev = t;
928       t = t->next;
929     }
930   }
931   if (prev == NULL)
932   {
933     if (p == 0)
934     {
935       if (to == 0)
936       {
937         pending = t->next;
938       }
939       else
940       {
941         pending_timeout = t->next;
942       }
943     }
944     else
945     {
946       ready[p] = t->next;
947     }
948   }
949   else
950   {
951     prev->next = t->next;
952   }
953   ret = t->callback_cls;
954   LOG (GNUNET_ERROR_TYPE_DEBUG, "Canceling task: %llu / %p\n", task,
955        t->callback_cls);
956   destroy_task (t);
957   return ret;
958 }
959
960
961 /**
962  * Continue the current execution with the given function.  This is
963  * similar to the other "add" functions except that there is no delay
964  * and the reason code can be specified.
965  *
966  * @param task main function of the task
967  * @param task_cls closure for 'main'
968  * @param reason reason for task invocation
969  * @param priority priority to use for the task
970  */
971 void
972 GNUNET_SCHEDULER_add_continuation_with_priority (GNUNET_SCHEDULER_Task task, void *task_cls,
973                                                  enum GNUNET_SCHEDULER_Reason reason,
974                                                  enum GNUNET_SCHEDULER_Priority priority)
975 {
976   struct Task *t;
977
978 #if EXECINFO
979   void *backtrace_array[50];
980 #endif
981
982   GNUNET_assert (NULL != task);
983   GNUNET_assert ((active_task != NULL) ||
984                  (reason == GNUNET_SCHEDULER_REASON_STARTUP));
985   t = GNUNET_malloc (sizeof (struct Task));
986 #if EXECINFO
987   t->num_backtrace_strings = backtrace (backtrace_array, 50);
988   t->backtrace_strings =
989       backtrace_symbols (backtrace_array, t->num_backtrace_strings);
990 #endif
991   t->read_fd = -1;
992   t->write_fd = -1;
993   t->callback = task;
994   t->callback_cls = task_cls;
995   t->id = ++last_id;
996 #if PROFILE_DELAYS
997   t->start_time = GNUNET_TIME_absolute_get ();
998 #endif
999   t->reason = reason;
1000   t->priority = priority;
1001   t->lifeness = current_lifeness;
1002   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding continuation task: %llu / %p\n", t->id,
1003        t->callback_cls);
1004   queue_ready_task (t);
1005 }
1006
1007
1008 /**
1009  * Continue the current execution with the given function.  This is
1010  * similar to the other "add" functions except that there is no delay
1011  * and the reason code can be specified.
1012  *
1013  * @param task main function of the task
1014  * @param task_cls closure for 'main'
1015  * @param reason reason for task invocation
1016  */
1017 void
1018 GNUNET_SCHEDULER_add_continuation (GNUNET_SCHEDULER_Task task, void *task_cls,
1019                                    enum GNUNET_SCHEDULER_Reason reason)
1020 {
1021   GNUNET_SCHEDULER_add_continuation_with_priority (task, task_cls,
1022                                                    reason,
1023                                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT);
1024 }
1025
1026
1027 /**
1028  * Schedule a new task to be run with a specified priority.
1029  *
1030  * @param prio how important is the new task?
1031  * @param task main function of the task
1032  * @param task_cls closure of task
1033  * @return unique task identifier for the job
1034  *         only valid until "task" is started!
1035  */
1036 GNUNET_SCHEDULER_TaskIdentifier
1037 GNUNET_SCHEDULER_add_with_priority (enum GNUNET_SCHEDULER_Priority prio,
1038                                     GNUNET_SCHEDULER_Task task, void *task_cls)
1039 {
1040   return GNUNET_SCHEDULER_add_select (prio, 
1041                                       GNUNET_TIME_UNIT_ZERO, NULL, NULL, task,
1042                                       task_cls);
1043 }
1044
1045
1046
1047 /**
1048  * Schedule a new task to be run with a specified delay.  The task
1049  * will be scheduled for execution once the delay has expired.
1050  *
1051  * @param delay when should this operation time out? Use
1052  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1053  * @param priority priority to use for the task
1054  * @param task main function of the task
1055  * @param task_cls closure of task
1056  * @return unique task identifier for the job
1057  *         only valid until "task" is started!
1058  */
1059 GNUNET_SCHEDULER_TaskIdentifier
1060 GNUNET_SCHEDULER_add_delayed_with_priority (struct GNUNET_TIME_Relative delay,
1061                                             enum GNUNET_SCHEDULER_Priority priority,
1062                                             GNUNET_SCHEDULER_Task task, void *task_cls)
1063 {
1064   struct Task *t;
1065   struct Task *pos;
1066   struct Task *prev;
1067
1068 #if EXECINFO
1069   void *backtrace_array[MAX_TRACE_DEPTH];
1070 #endif
1071
1072   GNUNET_assert (active_task != NULL);
1073   GNUNET_assert (NULL != task);
1074   t = GNUNET_malloc (sizeof (struct Task));
1075   t->callback = task;
1076   t->callback_cls = task_cls;
1077 #if EXECINFO
1078   t->num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
1079   t->backtrace_strings =
1080       backtrace_symbols (backtrace_array, t->num_backtrace_strings);
1081 #endif
1082   t->read_fd = -1;
1083   t->write_fd = -1;
1084   t->id = ++last_id;
1085 #if PROFILE_DELAYS
1086   t->start_time = GNUNET_TIME_absolute_get ();
1087 #endif
1088   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1089   t->priority = priority;
1090   t->lifeness = current_lifeness;
1091   /* try tail first (optimization in case we are
1092    * appending to a long list of tasks with timeouts) */
1093   prev = pending_timeout_last;
1094   if (prev != NULL)
1095   {
1096     if (prev->timeout.abs_value > t->timeout.abs_value)
1097       prev = NULL;
1098     else
1099       pos = prev->next;         /* heuristic success! */
1100   }
1101   if (prev == NULL)
1102   {
1103     /* heuristic failed, do traversal of timeout list */
1104     pos = pending_timeout;
1105   }
1106   while ((pos != NULL) &&
1107          ((pos->timeout.abs_value <= t->timeout.abs_value) ||
1108           (pos->reason != 0)))
1109   {
1110     prev = pos;
1111     pos = pos->next;
1112   }
1113   if (prev == NULL)
1114     pending_timeout = t;
1115   else
1116     prev->next = t;
1117   t->next = pos;
1118   /* hyper-optimization... */
1119   pending_timeout_last = t;
1120
1121   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding task: %llu / %p\n", t->id,
1122        t->callback_cls);
1123 #if EXECINFO
1124   int i;
1125
1126   for (i = 0; i < t->num_backtrace_strings; i++)
1127     LOG (GNUNET_ERROR_TYPE_DEBUG, "Task %llu trace %d: %s\n", t->id, i,
1128          t->backtrace_strings[i]);
1129 #endif
1130   return t->id;
1131 }
1132
1133
1134 /**
1135  * Schedule a new task to be run with a specified delay.  The task
1136  * will be scheduled for execution once the delay has expired. It
1137  * will be run with the DEFAULT priority.
1138  *
1139  * @param delay when should this operation time out? Use
1140  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1141  * @param task main function of the task
1142  * @param task_cls closure of task
1143  * @return unique task identifier for the job
1144  *         only valid until "task" is started!
1145  */
1146 GNUNET_SCHEDULER_TaskIdentifier
1147 GNUNET_SCHEDULER_add_delayed (struct GNUNET_TIME_Relative delay,
1148                               GNUNET_SCHEDULER_Task task, void *task_cls)
1149 {
1150   return GNUNET_SCHEDULER_add_delayed_with_priority (delay,
1151                                                      GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1152                                                      task, task_cls);
1153 }
1154
1155
1156 /**
1157  * Schedule a new task to be run as soon as possible. The task
1158  * will be run with the DEFAULT priority.
1159  *
1160  * @param task main function of the task
1161  * @param task_cls closure of task
1162  * @return unique task identifier for the job
1163  *         only valid until "task" is started!
1164  */
1165 GNUNET_SCHEDULER_TaskIdentifier
1166 GNUNET_SCHEDULER_add_now (GNUNET_SCHEDULER_Task task, void *task_cls)
1167 {
1168   return GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_ZERO, task, task_cls);
1169 }
1170
1171
1172 /**
1173  * Schedule a new task to be run as soon as possible with the
1174  * (transitive) ignore-shutdown flag either explicitly set or
1175  * explicitly enabled.  This task (and all tasks created from it,
1176  * other than by another call to this function) will either count or
1177  * not count for the 'lifeness' of the process.  This API is only
1178  * useful in a few special cases.
1179  *
1180  * @param lifeness GNUNET_YES if the task counts for lifeness, GNUNET_NO if not.
1181  * @param task main function of the task
1182  * @param task_cls closure of task
1183  * @return unique task identifier for the job
1184  *         only valid until "task" is started!
1185  */
1186 GNUNET_SCHEDULER_TaskIdentifier
1187 GNUNET_SCHEDULER_add_now_with_lifeness (int lifeness,
1188                                         GNUNET_SCHEDULER_Task task,
1189                                         void *task_cls)
1190 {
1191   GNUNET_SCHEDULER_TaskIdentifier ret;
1192
1193   ret =
1194       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1195                                    GNUNET_TIME_UNIT_ZERO, NULL, NULL, task,
1196                                    task_cls);
1197   GNUNET_assert (pending->id == ret);
1198   pending->lifeness = lifeness;
1199   return ret;
1200 }
1201
1202
1203 /**
1204  * Schedule a new task to be run with a specified delay or when any of
1205  * the specified file descriptor sets is ready.  The delay can be used
1206  * as a timeout on the socket(s) being ready.  The task will be
1207  * scheduled for execution once either the delay has expired or any of
1208  * the socket operations is ready.  This is the most general
1209  * function of the "add" family.  Note that the "prerequisite_task"
1210  * must be satisfied in addition to any of the other conditions.  In
1211  * other words, the task will be started when
1212  * <code>
1213  * (prerequisite-run)
1214  * && (delay-ready
1215  *     || any-rs-ready
1216  *     || any-ws-ready
1217  *     || shutdown-active )
1218  * </code>
1219  *
1220  * @param delay how long should we wait? Use GNUNET_TIME_UNIT_FOREVER_REL for "forever",
1221  *        which means that the task will only be run after we receive SIGTERM
1222  * @param priority priority to use
1223  * @param rfd file descriptor we want to read (can be -1)
1224  * @param wfd file descriptors we want to write (can be -1)
1225  * @param task main function of the task
1226  * @param task_cls closure of task
1227  * @return unique task identifier for the job
1228  *         only valid until "task" is started!
1229  */
1230 #ifndef MINGW
1231 static GNUNET_SCHEDULER_TaskIdentifier
1232 add_without_sets (struct GNUNET_TIME_Relative delay, 
1233                   enum GNUNET_SCHEDULER_Priority priority,
1234                   int rfd, int wfd,
1235                   GNUNET_SCHEDULER_Task task, void *task_cls)
1236 {
1237   struct Task *t;
1238
1239 #if EXECINFO
1240   void *backtrace_array[MAX_TRACE_DEPTH];
1241 #endif
1242
1243   GNUNET_assert (active_task != NULL);
1244   GNUNET_assert (NULL != task);
1245   t = GNUNET_malloc (sizeof (struct Task));
1246   t->callback = task;
1247   t->callback_cls = task_cls;
1248 #if EXECINFO
1249   t->num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
1250   t->backtrace_strings =
1251       backtrace_symbols (backtrace_array, t->num_backtrace_strings);
1252 #endif
1253 #if DEBUG_FDS
1254   if (-1 != rfd)
1255   {
1256     int flags = fcntl (rfd, F_GETFD);
1257
1258     if ((flags == -1) && (errno == EBADF))
1259     {
1260       LOG (GNUNET_ERROR_TYPE_ERROR, "Got invalid file descriptor %d!\n", rfd);
1261 #if EXECINFO
1262       int i;
1263
1264       for (i = 0; i < t->num_backtrace_strings; i++)
1265         LOG (GNUNET_ERROR_TYPE_DEBUG, "Trace: %s\n", t->backtrace_strings[i]);
1266 #endif
1267       GNUNET_assert (0);
1268     }
1269   }
1270   if (-1 != wfd)
1271   {
1272     int flags = fcntl (wfd, F_GETFD);
1273
1274     if (flags == -1 && errno == EBADF)
1275     {
1276       LOG (GNUNET_ERROR_TYPE_ERROR, "Got invalid file descriptor %d!\n", wfd);
1277 #if EXECINFO
1278       int i;
1279
1280       for (i = 0; i < t->num_backtrace_strings; i++)
1281         LOG (GNUNET_ERROR_TYPE_DEBUG, "Trace: %s\n", t->backtrace_strings[i]);
1282 #endif
1283       GNUNET_assert (0);
1284     }
1285   }
1286 #endif
1287   t->read_fd = rfd;
1288   GNUNET_assert (wfd >= -1);
1289   t->write_fd = wfd;
1290   t->id = ++last_id;
1291 #if PROFILE_DELAYS
1292   t->start_time = GNUNET_TIME_absolute_get ();
1293 #endif
1294   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1295   t->priority = check_priority ((priority == GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority : priority);
1296   t->lifeness = current_lifeness;
1297   t->next = pending;
1298   pending = t;
1299   max_priority_added = GNUNET_MAX (max_priority_added, t->priority);
1300   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding task: %llu / %p\n", t->id,
1301        t->callback_cls);
1302 #if EXECINFO
1303   int i;
1304
1305   for (i = 0; i < t->num_backtrace_strings; i++)
1306     LOG (GNUNET_ERROR_TYPE_DEBUG, "Task %llu trace %d: %s\n", t->id, i,
1307          t->backtrace_strings[i]);
1308 #endif
1309   return t->id;
1310 }
1311 #endif
1312
1313
1314
1315 /**
1316  * Schedule a new task to be run with a specified delay or when the
1317  * specified file descriptor is ready for reading.  The delay can be
1318  * used as a timeout on the socket being ready.  The task will be
1319  * scheduled for execution once either the delay has expired or the
1320  * socket operation is ready.  It will be run with the DEFAULT priority.
1321  *
1322  * @param delay when should this operation time out? Use
1323  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1324  * @param rfd read file-descriptor
1325  * @param task main function of the task
1326  * @param task_cls closure of task
1327  * @return unique task identifier for the job
1328  *         only valid until "task" is started!
1329  */
1330 GNUNET_SCHEDULER_TaskIdentifier
1331 GNUNET_SCHEDULER_add_read_net (struct GNUNET_TIME_Relative delay,
1332                                struct GNUNET_NETWORK_Handle *rfd,
1333                                GNUNET_SCHEDULER_Task task, void *task_cls)
1334 {
1335   return GNUNET_SCHEDULER_add_read_net_with_priority (delay,
1336                                                       GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1337                                                       rfd, task, task_cls);
1338 }
1339
1340
1341 /**
1342  * Schedule a new task to be run with a specified priority and to be
1343  * run after the specified delay or when the specified file descriptor
1344  * is ready for reading.  The delay can be used as a timeout on the
1345  * socket being ready.  The task will be scheduled for execution once
1346  * either the delay has expired or the socket operation is ready.  It
1347  * will be run with the DEFAULT priority.
1348  *
1349  * @param delay when should this operation time out? Use
1350  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1351  * @param priority priority to use for the task
1352  * @param rfd read file-descriptor
1353  * @param task main function of the task
1354  * @param task_cls closure of task
1355  * @return unique task identifier for the job
1356  *         only valid until "task" is started!
1357  */
1358 GNUNET_SCHEDULER_TaskIdentifier
1359 GNUNET_SCHEDULER_add_read_net_with_priority (struct GNUNET_TIME_Relative delay,
1360                                              enum GNUNET_SCHEDULER_Priority priority,
1361                                              struct GNUNET_NETWORK_Handle *rfd,
1362                                              GNUNET_SCHEDULER_Task task, void *task_cls)
1363 {
1364 #if MINGW
1365   struct GNUNET_NETWORK_FDSet *rs;
1366   GNUNET_SCHEDULER_TaskIdentifier ret;
1367
1368   GNUNET_assert (rfd != NULL);
1369   rs = GNUNET_NETWORK_fdset_create ();
1370   GNUNET_NETWORK_fdset_set (rs, rfd);
1371   ret =
1372     GNUNET_SCHEDULER_add_select (priority,
1373                                  delay, rs, NULL,
1374                                  task, task_cls);
1375   GNUNET_NETWORK_fdset_destroy (rs);
1376   return ret;
1377 #else
1378   return add_without_sets (delay, 
1379                            priority,
1380                            GNUNET_NETWORK_get_fd (rfd), -1, task,
1381                            task_cls);
1382 #endif
1383 }
1384
1385
1386
1387 /**
1388  * Schedule a new task to be run with a specified delay or when the
1389  * specified file descriptor is ready for writing.  The delay can be
1390  * used as a timeout on the socket being ready.  The task will be
1391  * scheduled for execution once either the delay has expired or the
1392  * socket operation is ready.  It will be run with the priority of
1393  * the calling task.
1394  *
1395  * @param delay when should this operation time out? Use
1396  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1397  * @param wfd write file-descriptor
1398  * @param task main function of the task
1399  * @param task_cls closure of task
1400  * @return unique task identifier for the job
1401  *         only valid until "task" is started!
1402  */
1403 GNUNET_SCHEDULER_TaskIdentifier
1404 GNUNET_SCHEDULER_add_write_net (struct GNUNET_TIME_Relative delay,
1405                                 struct GNUNET_NETWORK_Handle *wfd,
1406                                 GNUNET_SCHEDULER_Task task, void *task_cls)
1407 {
1408 #if MINGW
1409   struct GNUNET_NETWORK_FDSet *ws;
1410   GNUNET_SCHEDULER_TaskIdentifier ret;
1411
1412   GNUNET_assert (wfd != NULL);
1413   ws = GNUNET_NETWORK_fdset_create ();
1414   GNUNET_NETWORK_fdset_set (ws, wfd);
1415   ret =
1416     GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1417                                  delay, NULL, ws,
1418                                    task, task_cls);
1419   GNUNET_NETWORK_fdset_destroy (ws);
1420   return ret;
1421 #else
1422   GNUNET_assert (GNUNET_NETWORK_get_fd (wfd) >= 0);
1423   return add_without_sets (delay, 
1424                            GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1425                            -1, GNUNET_NETWORK_get_fd (wfd), task,
1426                            task_cls);
1427 #endif
1428 }
1429
1430
1431 /**
1432  * Schedule a new task to be run with a specified delay or when the
1433  * specified file descriptor is ready for reading.  The delay can be
1434  * used as a timeout on the socket being ready.  The task will be
1435  * scheduled for execution once either the delay has expired or the
1436  * socket operation is ready. It will be run with the DEFAULT priority.
1437  *
1438  * @param delay when should this operation time out? Use
1439  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1440  * @param rfd read file-descriptor
1441  * @param task main function of the task
1442  * @param task_cls closure of task
1443  * @return unique task identifier for the job
1444  *         only valid until "task" is started!
1445  */
1446 GNUNET_SCHEDULER_TaskIdentifier
1447 GNUNET_SCHEDULER_add_read_file (struct GNUNET_TIME_Relative delay,
1448                                 const struct GNUNET_DISK_FileHandle *rfd,
1449                                 GNUNET_SCHEDULER_Task task, void *task_cls)
1450 {
1451 #if MINGW
1452   struct GNUNET_NETWORK_FDSet *rs;
1453   GNUNET_SCHEDULER_TaskIdentifier ret;
1454
1455   GNUNET_assert (rfd != NULL);
1456   rs = GNUNET_NETWORK_fdset_create ();
1457   GNUNET_NETWORK_fdset_handle_set (rs, rfd);
1458   ret =
1459       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1460                                    delay, rs, NULL,
1461                                    task, task_cls);
1462   GNUNET_NETWORK_fdset_destroy (rs);
1463   return ret;
1464 #else
1465   int fd;
1466
1467   GNUNET_DISK_internal_file_handle_ (rfd, &fd, sizeof (int));
1468   return add_without_sets (delay, 
1469                            GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1470                            fd, -1, task, task_cls);
1471
1472 #endif
1473 }
1474
1475
1476 /**
1477  * Schedule a new task to be run with a specified delay or when the
1478  * specified file descriptor is ready for writing.  The delay can be
1479  * used as a timeout on the socket being ready.  The task will be
1480  * scheduled for execution once either the delay has expired or the
1481  * socket operation is ready. It will be run with the DEFAULT priority.
1482  *
1483  * @param delay when should this operation time out? Use
1484  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1485  * @param wfd write file-descriptor
1486  * @param task main function of the task
1487  * @param task_cls closure of task
1488  * @return unique task identifier for the job
1489  *         only valid until "task" is started!
1490  */
1491 GNUNET_SCHEDULER_TaskIdentifier
1492 GNUNET_SCHEDULER_add_write_file (struct GNUNET_TIME_Relative delay,
1493                                  const struct GNUNET_DISK_FileHandle *wfd,
1494                                  GNUNET_SCHEDULER_Task task, void *task_cls)
1495 {
1496 #if MINGW
1497   struct GNUNET_NETWORK_FDSet *ws;
1498   GNUNET_SCHEDULER_TaskIdentifier ret;
1499
1500   GNUNET_assert (wfd != NULL);
1501   ws = GNUNET_NETWORK_fdset_create ();
1502   GNUNET_NETWORK_fdset_handle_set (ws, wfd);
1503   ret =
1504       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1505                                    delay, NULL, ws,
1506                                    task, task_cls);
1507   GNUNET_NETWORK_fdset_destroy (ws);
1508   return ret;
1509 #else
1510   int fd;
1511
1512   GNUNET_DISK_internal_file_handle_ (wfd, &fd, sizeof (int));
1513   GNUNET_assert (fd >= 0);
1514   return add_without_sets (delay, 
1515                            GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1516                            -1, fd, task, task_cls);
1517
1518 #endif
1519 }
1520
1521
1522
1523 /**
1524  * Schedule a new task to be run with a specified delay or when any of
1525  * the specified file descriptor sets is ready.  The delay can be used
1526  * as a timeout on the socket(s) being ready.  The task will be
1527  * scheduled for execution once either the delay has expired or any of
1528  * the socket operations is ready.  This is the most general
1529  * function of the "add" family.  Note that the "prerequisite_task"
1530  * must be satisfied in addition to any of the other conditions.  In
1531  * other words, the task will be started when
1532  * <code>
1533  * (prerequisite-run)
1534  * && (delay-ready
1535  *     || any-rs-ready
1536  *     || any-ws-ready
1537  *     || (shutdown-active && run-on-shutdown) )
1538  * </code>
1539  *
1540  * @param prio how important is this task?
1541  * @param delay how long should we wait? Use GNUNET_TIME_UNIT_FOREVER_REL for "forever",
1542  *        which means that the task will only be run after we receive SIGTERM
1543  * @param rs set of file descriptors we want to read (can be NULL)
1544  * @param ws set of file descriptors we want to write (can be NULL)
1545  * @param task main function of the task
1546  * @param task_cls closure of task
1547  * @return unique task identifier for the job
1548  *         only valid until "task" is started!
1549  */
1550 GNUNET_SCHEDULER_TaskIdentifier
1551 GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio,
1552                              struct GNUNET_TIME_Relative delay,
1553                              const struct GNUNET_NETWORK_FDSet *rs,
1554                              const struct GNUNET_NETWORK_FDSet *ws,
1555                              GNUNET_SCHEDULER_Task task, void *task_cls)
1556 {
1557   struct Task *t;
1558
1559 #if EXECINFO
1560   void *backtrace_array[MAX_TRACE_DEPTH];
1561 #endif
1562
1563   GNUNET_assert (active_task != NULL);
1564   GNUNET_assert (NULL != task);
1565   t = GNUNET_malloc (sizeof (struct Task));
1566   t->callback = task;
1567   t->callback_cls = task_cls;
1568 #if EXECINFO
1569   t->num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
1570   t->backtrace_strings =
1571       backtrace_symbols (backtrace_array, t->num_backtrace_strings);
1572 #endif
1573   t->read_fd = -1;
1574   t->write_fd = -1;
1575   if (rs != NULL)
1576   {
1577     t->read_set = GNUNET_NETWORK_fdset_create ();
1578     GNUNET_NETWORK_fdset_copy (t->read_set, rs);
1579   }
1580   if (ws != NULL)
1581   {
1582     t->write_set = GNUNET_NETWORK_fdset_create ();
1583     GNUNET_NETWORK_fdset_copy (t->write_set, ws);
1584   }
1585   t->id = ++last_id;
1586 #if PROFILE_DELAYS
1587   t->start_time = GNUNET_TIME_absolute_get ();
1588 #endif
1589   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1590   t->priority =
1591       check_priority ((prio ==
1592                        GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority :
1593                       prio);
1594   t->lifeness = current_lifeness;
1595   t->next = pending;
1596   pending = t;
1597   max_priority_added = GNUNET_MAX (max_priority_added, t->priority);
1598   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding task: %llu / %p\n", t->id,
1599        t->callback_cls);
1600 #if EXECINFO
1601   int i;
1602
1603   for (i = 0; i < t->num_backtrace_strings; i++)
1604     LOG (GNUNET_ERROR_TYPE_DEBUG, "Task %llu trace %d: %s\n", t->id, i,
1605          t->backtrace_strings[i]);
1606 #endif
1607   return t->id;
1608 }
1609
1610 /* end of scheduler.c */