-test for execinfo.h instead of LINUX
[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     if (current_priority != pos->priority)
569     {
570       current_priority = pos->priority;
571       (void) GNUNET_OS_set_process_priority (GNUNET_OS_process_current (),
572                                              pos->priority);
573     }
574     current_lifeness = pos->lifeness;
575     active_task = pos;
576 #if PROFILE_DELAYS
577     if (GNUNET_TIME_absolute_get_duration (pos->start_time).rel_value >
578         DELAY_THRESHOLD.rel_value)
579     {
580       LOG (GNUNET_ERROR_TYPE_ERROR, "Task %llu took %llums to be scheduled\n",
581            pos->id,
582            (unsigned long long)
583            GNUNET_TIME_absolute_get_duration (pos->start_time).rel_value);
584     }
585 #endif
586     tc.reason = pos->reason;
587     tc.read_ready = (pos->read_set == NULL) ? rs : pos->read_set;
588     if ((pos->read_fd != -1) &&
589         (0 != (pos->reason & GNUNET_SCHEDULER_REASON_READ_READY)))
590       GNUNET_NETWORK_fdset_set_native (rs, pos->read_fd);
591     tc.write_ready = (pos->write_set == NULL) ? ws : pos->write_set;
592     if ((pos->write_fd != -1) &&
593         (0 != (pos->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)))
594       GNUNET_NETWORK_fdset_set_native (ws, pos->write_fd);
595     if (((tc.reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0) &&
596         (pos->write_fd != -1) &&
597         (!GNUNET_NETWORK_fdset_test_native (ws, pos->write_fd)))
598       GNUNET_abort ();          // added to ready in previous select loop!
599     LOG (GNUNET_ERROR_TYPE_DEBUG, 
600          "Running task: %llu / %p\n", pos->id,
601          pos->callback_cls);
602     pos->callback (pos->callback_cls, &tc);
603 #if EXECINFO
604     int i;
605
606     for (i = 0; i < pos->num_backtrace_strings; i++)
607       LOG (GNUNET_ERROR_TYPE_ERROR, "Task %llu trace %d: %s\n", pos->id, i,
608            pos->backtrace_strings[i]);
609 #endif
610     active_task = NULL;
611     destroy_task (pos);
612     tasks_run++;
613   }
614   while ((pending == NULL) || (p >= max_priority_added));
615 }
616
617 /**
618  * Pipe used to communicate shutdown via signal.
619  */
620 static struct GNUNET_DISK_PipeHandle *shutdown_pipe_handle;
621
622 /**
623  * Process ID of this process at the time we installed the various
624  * signal handlers.
625  */
626 static pid_t my_pid;
627
628 /**
629  * Signal handler called for SIGPIPE.
630  */
631 #ifndef MINGW
632 static void
633 sighandler_pipe ()
634 {
635   return;
636 }
637 #endif
638 /**
639  * Signal handler called for signals that should cause us to shutdown.
640  */
641 static void
642 sighandler_shutdown ()
643 {
644   static char c;
645   int old_errno = errno;        /* backup errno */
646
647   if (getpid () != my_pid)
648     exit (1);                   /* we have fork'ed since the signal handler was created,
649                                  * ignore the signal, see https://gnunet.org/vfork discussion */
650   GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
651                           (shutdown_pipe_handle, GNUNET_DISK_PIPE_END_WRITE),
652                           &c, sizeof (c));
653   errno = old_errno;
654 }
655
656
657 /**
658  * Check if the system is still life. Trigger shutdown if we
659  * have tasks, but none of them give us lifeness.
660  *
661  * @return GNUNET_OK to continue the main loop,
662  *         GNUNET_NO to exit
663  */
664 static int
665 check_lifeness ()
666 {
667   struct Task *t;
668
669   if (ready_count > 0)
670     return GNUNET_OK;
671   for (t = pending; NULL != t; t = t->next)
672     if (t->lifeness == GNUNET_YES)
673       return GNUNET_OK;
674   for (t = pending_timeout; NULL != t; t = t->next)
675     if (t->lifeness == GNUNET_YES)
676       return GNUNET_OK;
677   if ((NULL != pending) || (NULL != pending_timeout))
678   {
679     GNUNET_SCHEDULER_shutdown ();
680     return GNUNET_OK;
681   }
682   return GNUNET_NO;
683 }
684
685
686 /**
687  * Initialize and run scheduler.  This function will return when all
688  * tasks have completed.  On systems with signals, receiving a SIGTERM
689  * (and other similar signals) will cause "GNUNET_SCHEDULER_shutdown"
690  * to be run after the active task is complete.  As a result, SIGTERM
691  * causes all active tasks to be scheduled with reason
692  * "GNUNET_SCHEDULER_REASON_SHUTDOWN".  (However, tasks added
693  * afterwards will execute normally!). Note that any particular signal
694  * will only shut down one scheduler; applications should always only
695  * create a single scheduler.
696  *
697  * @param task task to run immediately
698  * @param task_cls closure of task
699  */
700 void
701 GNUNET_SCHEDULER_run (GNUNET_SCHEDULER_Task task, void *task_cls)
702 {
703   struct GNUNET_NETWORK_FDSet *rs;
704   struct GNUNET_NETWORK_FDSet *ws;
705   struct GNUNET_TIME_Relative timeout;
706   int ret;
707   struct GNUNET_SIGNAL_Context *shc_int;
708   struct GNUNET_SIGNAL_Context *shc_term;
709
710 #ifndef MINGW
711   struct GNUNET_SIGNAL_Context *shc_quit;
712   struct GNUNET_SIGNAL_Context *shc_hup;
713   struct GNUNET_SIGNAL_Context *shc_pipe;
714 #endif
715   unsigned long long last_tr;
716   unsigned int busy_wait_warning;
717   const struct GNUNET_DISK_FileHandle *pr;
718   char c;
719
720   GNUNET_assert (active_task == NULL);
721   rs = GNUNET_NETWORK_fdset_create ();
722   ws = GNUNET_NETWORK_fdset_create ();
723   GNUNET_assert (shutdown_pipe_handle == NULL);
724   shutdown_pipe_handle = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO);
725   GNUNET_assert (shutdown_pipe_handle != NULL);
726   pr = GNUNET_DISK_pipe_handle (shutdown_pipe_handle,
727                                 GNUNET_DISK_PIPE_END_READ);
728   GNUNET_assert (pr != NULL);
729   my_pid = getpid ();
730   shc_int = GNUNET_SIGNAL_handler_install (SIGINT, &sighandler_shutdown);
731   shc_term = GNUNET_SIGNAL_handler_install (SIGTERM, &sighandler_shutdown);
732 #ifndef MINGW
733   shc_pipe = GNUNET_SIGNAL_handler_install (SIGPIPE, &sighandler_pipe);
734   shc_quit = GNUNET_SIGNAL_handler_install (SIGQUIT, &sighandler_shutdown);
735   shc_hup = GNUNET_SIGNAL_handler_install (SIGHUP, &sighandler_shutdown);
736 #endif
737   current_priority = GNUNET_SCHEDULER_PRIORITY_DEFAULT;
738   current_lifeness = GNUNET_YES;
739   GNUNET_SCHEDULER_add_continuation (task, task_cls,
740                                      GNUNET_SCHEDULER_REASON_STARTUP);
741   active_task = (void *) (long) -1;     /* force passing of sanity check */
742   GNUNET_SCHEDULER_add_now_with_lifeness (GNUNET_NO,
743                                           &GNUNET_OS_install_parent_control_handler,
744                                           NULL);
745   active_task = NULL;
746   last_tr = 0;
747   busy_wait_warning = 0;
748   while (GNUNET_OK == check_lifeness ())
749   {
750     GNUNET_NETWORK_fdset_zero (rs);
751     GNUNET_NETWORK_fdset_zero (ws);
752     timeout = GNUNET_TIME_UNIT_FOREVER_REL;
753     update_sets (rs, ws, &timeout);
754     GNUNET_NETWORK_fdset_handle_set (rs, pr);
755     if (ready_count > 0)
756     {
757       /* no blocking, more work already ready! */
758       timeout = GNUNET_TIME_UNIT_ZERO;
759     }
760     if (NULL == scheduler_select)
761       ret = GNUNET_NETWORK_socket_select (rs, ws, NULL, timeout);
762     else
763       ret = scheduler_select (scheduler_select_cls, rs, ws, NULL, timeout);
764     if (ret == GNUNET_SYSERR)
765     {
766       if (errno == EINTR)
767         continue;
768
769       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "select");
770 #ifndef MINGW
771 #if USE_LSOF
772       char lsof[512];
773
774       snprintf (lsof, sizeof (lsof), "lsof -p %d", getpid ());
775       (void) close (1);
776       (void) dup2 (2, 1);
777       if (0 != system (lsof))
778         LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "system");
779 #endif
780 #endif
781       GNUNET_abort ();
782       break;
783     }
784     if ((ret == 0) && (timeout.rel_value == 0) && (busy_wait_warning > 16))
785     {
786       LOG (GNUNET_ERROR_TYPE_WARNING, _("Looks like we're busy waiting...\n"));
787       sleep (1);                /* mitigate */
788     }
789     check_ready (rs, ws);
790     run_ready (rs, ws);
791     if (GNUNET_NETWORK_fdset_handle_isset (rs, pr))
792     {
793       /* consume the signal */
794       GNUNET_DISK_file_read (pr, &c, sizeof (c));
795       /* mark all active tasks as ready due to shutdown */
796       GNUNET_SCHEDULER_shutdown ();
797     }
798     if (last_tr == tasks_run)
799     {
800       busy_wait_warning++;
801     }
802     else
803     {
804       last_tr = tasks_run;
805       busy_wait_warning = 0;
806     }
807   }
808   GNUNET_SIGNAL_handler_uninstall (shc_int);
809   GNUNET_SIGNAL_handler_uninstall (shc_term);
810 #ifndef MINGW
811   GNUNET_SIGNAL_handler_uninstall (shc_pipe);
812   GNUNET_SIGNAL_handler_uninstall (shc_quit);
813   GNUNET_SIGNAL_handler_uninstall (shc_hup);
814 #endif
815   GNUNET_DISK_pipe_close (shutdown_pipe_handle);
816   shutdown_pipe_handle = NULL;
817   GNUNET_NETWORK_fdset_destroy (rs);
818   GNUNET_NETWORK_fdset_destroy (ws);
819 }
820
821
822 /**
823  * Obtain the reason code for why the current task was
824  * started.  Will return the same value as
825  * the GNUNET_SCHEDULER_TaskContext's reason field.
826  *
827  * @return reason(s) why the current task is run
828  */
829 enum GNUNET_SCHEDULER_Reason
830 GNUNET_SCHEDULER_get_reason ()
831 {
832   GNUNET_assert (active_task != NULL);
833   return active_task->reason;
834 }
835
836
837 /**
838  * Get information about the current load of this scheduler.  Use this
839  * function to determine if an elective task should be added or simply
840  * dropped (if the decision should be made based on the number of
841  * tasks ready to run).
842  *
843  * @param p priority level to look at
844  * @return number of tasks pending right now
845  */
846 unsigned int
847 GNUNET_SCHEDULER_get_load (enum GNUNET_SCHEDULER_Priority p)
848 {
849   struct Task *pos;
850   unsigned int ret;
851
852   GNUNET_assert (active_task != NULL);
853   if (p == GNUNET_SCHEDULER_PRIORITY_COUNT)
854     return ready_count;
855   if (p == GNUNET_SCHEDULER_PRIORITY_KEEP)
856     p = current_priority;
857   ret = 0;
858   pos = ready[check_priority (p)];
859   while (pos != NULL)
860   {
861     pos = pos->next;
862     ret++;
863   }
864   return ret;
865 }
866
867
868 /**
869  * Cancel the task with the specified identifier.
870  * The task must not yet have run.
871  *
872  * @param task id of the task to cancel
873  * @return original closure of the task
874  */
875 void *
876 GNUNET_SCHEDULER_cancel (GNUNET_SCHEDULER_TaskIdentifier task)
877 {
878   struct Task *t;
879   struct Task *prev;
880   enum GNUNET_SCHEDULER_Priority p;
881   int to;
882   void *ret;
883
884   GNUNET_assert (active_task != NULL);
885   to = 0;
886   prev = NULL;
887   t = pending;
888   while (t != NULL)
889   {
890     if (t->id == task)
891       break;
892     prev = t;
893     t = t->next;
894   }
895   if (t == NULL)
896   {
897     prev = NULL;
898     to = 1;
899     t = pending_timeout;
900     while (t != NULL)
901     {
902       if (t->id == task)
903         break;
904       prev = t;
905       t = t->next;
906     }
907     if (pending_timeout_last == t)
908       pending_timeout_last = NULL;
909   }
910   p = 0;
911   while (t == NULL)
912   {
913     p++;
914     if (p >= GNUNET_SCHEDULER_PRIORITY_COUNT)
915     {
916       LOG (GNUNET_ERROR_TYPE_ERROR, _("Attempt to cancel dead task %llu!\n"),
917            (unsigned long long) task);
918       GNUNET_assert (0);
919     }
920     prev = NULL;
921     t = ready[p];
922     while (t != NULL)
923     {
924       if (t->id == task)
925       {
926         ready_count--;
927         break;
928       }
929       prev = t;
930       t = t->next;
931     }
932   }
933   if (prev == NULL)
934   {
935     if (p == 0)
936     {
937       if (to == 0)
938       {
939         pending = t->next;
940       }
941       else
942       {
943         pending_timeout = t->next;
944       }
945     }
946     else
947     {
948       ready[p] = t->next;
949     }
950   }
951   else
952   {
953     prev->next = t->next;
954   }
955   ret = t->callback_cls;
956   LOG (GNUNET_ERROR_TYPE_DEBUG, "Canceling task: %llu / %p\n", task,
957        t->callback_cls);
958   destroy_task (t);
959   return ret;
960 }
961
962
963 /**
964  * Continue the current execution with the given function.  This is
965  * similar to the other "add" functions except that there is no delay
966  * and the reason code can be specified.
967  *
968  * @param task main function of the task
969  * @param task_cls closure for 'main'
970  * @param reason reason for task invocation
971  * @param priority priority to use for the task
972  */
973 void
974 GNUNET_SCHEDULER_add_continuation_with_priority (GNUNET_SCHEDULER_Task task, void *task_cls,
975                                                  enum GNUNET_SCHEDULER_Reason reason,
976                                                  enum GNUNET_SCHEDULER_Priority priority)
977 {
978   struct Task *t;
979
980 #if EXECINFO
981   void *backtrace_array[50];
982 #endif
983
984   GNUNET_assert (NULL != task);
985   GNUNET_assert ((active_task != NULL) ||
986                  (reason == GNUNET_SCHEDULER_REASON_STARTUP));
987   t = GNUNET_malloc (sizeof (struct Task));
988 #if EXECINFO
989   t->num_backtrace_strings = backtrace (backtrace_array, 50);
990   t->backtrace_strings =
991       backtrace_symbols (backtrace_array, t->num_backtrace_strings);
992 #endif
993   t->read_fd = -1;
994   t->write_fd = -1;
995   t->callback = task;
996   t->callback_cls = task_cls;
997   t->id = ++last_id;
998 #if PROFILE_DELAYS
999   t->start_time = GNUNET_TIME_absolute_get ();
1000 #endif
1001   t->reason = reason;
1002   t->priority = priority;
1003   t->lifeness = current_lifeness;
1004   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding continuation task: %llu / %p\n", t->id,
1005        t->callback_cls);
1006   queue_ready_task (t);
1007 }
1008
1009
1010 /**
1011  * Continue the current execution with the given function.  This is
1012  * similar to the other "add" functions except that there is no delay
1013  * and the reason code can be specified.
1014  *
1015  * @param task main function of the task
1016  * @param task_cls closure for 'main'
1017  * @param reason reason for task invocation
1018  */
1019 void
1020 GNUNET_SCHEDULER_add_continuation (GNUNET_SCHEDULER_Task task, void *task_cls,
1021                                    enum GNUNET_SCHEDULER_Reason reason)
1022 {
1023   GNUNET_SCHEDULER_add_continuation_with_priority (task, task_cls,
1024                                                    reason,
1025                                                    GNUNET_SCHEDULER_PRIORITY_DEFAULT);
1026 }
1027
1028
1029 /**
1030  * Schedule a new task to be run with a specified priority.
1031  *
1032  * @param prio how important is the new task?
1033  * @param task main function of the task
1034  * @param task_cls closure of task
1035  * @return unique task identifier for the job
1036  *         only valid until "task" is started!
1037  */
1038 GNUNET_SCHEDULER_TaskIdentifier
1039 GNUNET_SCHEDULER_add_with_priority (enum GNUNET_SCHEDULER_Priority prio,
1040                                     GNUNET_SCHEDULER_Task task, void *task_cls)
1041 {
1042   return GNUNET_SCHEDULER_add_select (prio, 
1043                                       GNUNET_TIME_UNIT_ZERO, NULL, NULL, task,
1044                                       task_cls);
1045 }
1046
1047
1048
1049 /**
1050  * Schedule a new task to be run with a specified delay.  The task
1051  * will be scheduled for execution once the delay has expired.
1052  *
1053  * @param delay when should this operation time out? Use
1054  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1055  * @param priority priority to use for the task
1056  * @param task main function of the task
1057  * @param task_cls closure of task
1058  * @return unique task identifier for the job
1059  *         only valid until "task" is started!
1060  */
1061 GNUNET_SCHEDULER_TaskIdentifier
1062 GNUNET_SCHEDULER_add_delayed_with_priority (struct GNUNET_TIME_Relative delay,
1063                                             enum GNUNET_SCHEDULER_Priority priority,
1064                                             GNUNET_SCHEDULER_Task task, void *task_cls)
1065 {
1066   struct Task *t;
1067   struct Task *pos;
1068   struct Task *prev;
1069
1070 #if EXECINFO
1071   void *backtrace_array[MAX_TRACE_DEPTH];
1072 #endif
1073
1074   GNUNET_assert (active_task != NULL);
1075   GNUNET_assert (NULL != task);
1076   t = GNUNET_malloc (sizeof (struct Task));
1077   t->callback = task;
1078   t->callback_cls = task_cls;
1079 #if EXECINFO
1080   t->num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
1081   t->backtrace_strings =
1082       backtrace_symbols (backtrace_array, t->num_backtrace_strings);
1083 #endif
1084   t->read_fd = -1;
1085   t->write_fd = -1;
1086   t->id = ++last_id;
1087 #if PROFILE_DELAYS
1088   t->start_time = GNUNET_TIME_absolute_get ();
1089 #endif
1090   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1091   t->priority = priority;
1092   t->lifeness = current_lifeness;
1093   /* try tail first (optimization in case we are
1094    * appending to a long list of tasks with timeouts) */
1095   prev = pending_timeout_last;
1096   if (prev != NULL)
1097   {
1098     if (prev->timeout.abs_value > t->timeout.abs_value)
1099       prev = NULL;
1100     else
1101       pos = prev->next;         /* heuristic success! */
1102   }
1103   if (prev == NULL)
1104   {
1105     /* heuristic failed, do traversal of timeout list */
1106     pos = pending_timeout;
1107   }
1108   while ((pos != NULL) &&
1109          ((pos->timeout.abs_value <= t->timeout.abs_value) ||
1110           (pos->reason != 0)))
1111   {
1112     prev = pos;
1113     pos = pos->next;
1114   }
1115   if (prev == NULL)
1116     pending_timeout = t;
1117   else
1118     prev->next = t;
1119   t->next = pos;
1120   /* hyper-optimization... */
1121   pending_timeout_last = t;
1122
1123   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding task: %llu / %p\n", t->id,
1124        t->callback_cls);
1125 #if EXECINFO
1126   int i;
1127
1128   for (i = 0; i < t->num_backtrace_strings; i++)
1129     LOG (GNUNET_ERROR_TYPE_DEBUG, "Task %llu trace %d: %s\n", t->id, i,
1130          t->backtrace_strings[i]);
1131 #endif
1132   return t->id;
1133 }
1134
1135
1136 /**
1137  * Schedule a new task to be run with a specified delay.  The task
1138  * will be scheduled for execution once the delay has expired. It
1139  * will be run with the DEFAULT priority.
1140  *
1141  * @param delay when should this operation time out? Use
1142  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1143  * @param task main function of the task
1144  * @param task_cls closure of task
1145  * @return unique task identifier for the job
1146  *         only valid until "task" is started!
1147  */
1148 GNUNET_SCHEDULER_TaskIdentifier
1149 GNUNET_SCHEDULER_add_delayed (struct GNUNET_TIME_Relative delay,
1150                               GNUNET_SCHEDULER_Task task, void *task_cls)
1151 {
1152   return GNUNET_SCHEDULER_add_delayed_with_priority (delay,
1153                                                      GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1154                                                      task, task_cls);
1155 }
1156
1157
1158 /**
1159  * Schedule a new task to be run as soon as possible. The task
1160  * will be run with the DEFAULT priority.
1161  *
1162  * @param task main function of the task
1163  * @param task_cls closure of task
1164  * @return unique task identifier for the job
1165  *         only valid until "task" is started!
1166  */
1167 GNUNET_SCHEDULER_TaskIdentifier
1168 GNUNET_SCHEDULER_add_now (GNUNET_SCHEDULER_Task task, void *task_cls)
1169 {
1170   return GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_ZERO, task, task_cls);
1171 }
1172
1173
1174 /**
1175  * Schedule a new task to be run as soon as possible with the
1176  * (transitive) ignore-shutdown flag either explicitly set or
1177  * explicitly enabled.  This task (and all tasks created from it,
1178  * other than by another call to this function) will either count or
1179  * not count for the 'lifeness' of the process.  This API is only
1180  * useful in a few special cases.
1181  *
1182  * @param lifeness GNUNET_YES if the task counts for lifeness, GNUNET_NO if not.
1183  * @param task main function of the task
1184  * @param task_cls closure of task
1185  * @return unique task identifier for the job
1186  *         only valid until "task" is started!
1187  */
1188 GNUNET_SCHEDULER_TaskIdentifier
1189 GNUNET_SCHEDULER_add_now_with_lifeness (int lifeness,
1190                                         GNUNET_SCHEDULER_Task task,
1191                                         void *task_cls)
1192 {
1193   GNUNET_SCHEDULER_TaskIdentifier ret;
1194
1195   ret =
1196       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1197                                    GNUNET_TIME_UNIT_ZERO, NULL, NULL, task,
1198                                    task_cls);
1199   GNUNET_assert (pending->id == ret);
1200   pending->lifeness = lifeness;
1201   return ret;
1202 }
1203
1204
1205 /**
1206  * Schedule a new task to be run with a specified delay or when any of
1207  * the specified file descriptor sets is ready.  The delay can be used
1208  * as a timeout on the socket(s) being ready.  The task will be
1209  * scheduled for execution once either the delay has expired or any of
1210  * the socket operations is ready.  This is the most general
1211  * function of the "add" family.  Note that the "prerequisite_task"
1212  * must be satisfied in addition to any of the other conditions.  In
1213  * other words, the task will be started when
1214  * <code>
1215  * (prerequisite-run)
1216  * && (delay-ready
1217  *     || any-rs-ready
1218  *     || any-ws-ready
1219  *     || shutdown-active )
1220  * </code>
1221  *
1222  * @param delay how long should we wait? Use GNUNET_TIME_UNIT_FOREVER_REL for "forever",
1223  *        which means that the task will only be run after we receive SIGTERM
1224  * @param priority priority to use
1225  * @param rfd file descriptor we want to read (can be -1)
1226  * @param wfd file descriptors we want to write (can be -1)
1227  * @param task main function of the task
1228  * @param task_cls closure of task
1229  * @return unique task identifier for the job
1230  *         only valid until "task" is started!
1231  */
1232 #ifndef MINGW
1233 static GNUNET_SCHEDULER_TaskIdentifier
1234 add_without_sets (struct GNUNET_TIME_Relative delay, 
1235                   enum GNUNET_SCHEDULER_Priority priority,
1236                   int rfd, int wfd,
1237                   GNUNET_SCHEDULER_Task task, void *task_cls)
1238 {
1239   struct Task *t;
1240
1241 #if EXECINFO
1242   void *backtrace_array[MAX_TRACE_DEPTH];
1243 #endif
1244
1245   GNUNET_assert (active_task != NULL);
1246   GNUNET_assert (NULL != task);
1247   t = GNUNET_malloc (sizeof (struct Task));
1248   t->callback = task;
1249   t->callback_cls = task_cls;
1250 #if EXECINFO
1251   t->num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
1252   t->backtrace_strings =
1253       backtrace_symbols (backtrace_array, t->num_backtrace_strings);
1254 #endif
1255 #if DEBUG_FDS
1256   if (-1 != rfd)
1257   {
1258     int flags = fcntl (rfd, F_GETFD);
1259
1260     if ((flags == -1) && (errno == EBADF))
1261     {
1262       LOG (GNUNET_ERROR_TYPE_ERROR, "Got invalid file descriptor %d!\n", rfd);
1263 #if EXECINFO
1264       int i;
1265
1266       for (i = 0; i < t->num_backtrace_strings; i++)
1267         LOG (GNUNET_ERROR_TYPE_DEBUG, "Trace: %s\n", t->backtrace_strings[i]);
1268 #endif
1269       GNUNET_assert (0);
1270     }
1271   }
1272   if (-1 != wfd)
1273   {
1274     int flags = fcntl (wfd, F_GETFD);
1275
1276     if (flags == -1 && errno == EBADF)
1277     {
1278       LOG (GNUNET_ERROR_TYPE_ERROR, "Got invalid file descriptor %d!\n", wfd);
1279 #if EXECINFO
1280       int i;
1281
1282       for (i = 0; i < t->num_backtrace_strings; i++)
1283         LOG (GNUNET_ERROR_TYPE_DEBUG, "Trace: %s\n", t->backtrace_strings[i]);
1284 #endif
1285       GNUNET_assert (0);
1286     }
1287   }
1288 #endif
1289   t->read_fd = rfd;
1290   GNUNET_assert (wfd >= -1);
1291   t->write_fd = wfd;
1292   t->id = ++last_id;
1293 #if PROFILE_DELAYS
1294   t->start_time = GNUNET_TIME_absolute_get ();
1295 #endif
1296   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1297   t->priority = check_priority ((priority == GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority : priority);
1298   t->lifeness = current_lifeness;
1299   t->next = pending;
1300   pending = t;
1301   max_priority_added = GNUNET_MAX (max_priority_added, t->priority);
1302   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding task: %llu / %p\n", t->id,
1303        t->callback_cls);
1304 #if EXECINFO
1305   int i;
1306
1307   for (i = 0; i < t->num_backtrace_strings; i++)
1308     LOG (GNUNET_ERROR_TYPE_DEBUG, "Task %llu trace %d: %s\n", t->id, i,
1309          t->backtrace_strings[i]);
1310 #endif
1311   return t->id;
1312 }
1313 #endif
1314
1315
1316
1317 /**
1318  * Schedule a new task to be run with a specified delay or when the
1319  * specified file descriptor is ready for reading.  The delay can be
1320  * used as a timeout on the socket being ready.  The task will be
1321  * scheduled for execution once either the delay has expired or the
1322  * socket operation is ready.  It will be run with the DEFAULT priority.
1323  *
1324  * @param delay when should this operation time out? Use
1325  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1326  * @param rfd read file-descriptor
1327  * @param task main function of the task
1328  * @param task_cls closure of task
1329  * @return unique task identifier for the job
1330  *         only valid until "task" is started!
1331  */
1332 GNUNET_SCHEDULER_TaskIdentifier
1333 GNUNET_SCHEDULER_add_read_net (struct GNUNET_TIME_Relative delay,
1334                                struct GNUNET_NETWORK_Handle *rfd,
1335                                GNUNET_SCHEDULER_Task task, void *task_cls)
1336 {
1337   return GNUNET_SCHEDULER_add_read_net_with_priority (delay,
1338                                                       GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1339                                                       rfd, task, task_cls);
1340 }
1341
1342
1343 /**
1344  * Schedule a new task to be run with a specified priority and to be
1345  * run after the specified delay or when the specified file descriptor
1346  * is ready for reading.  The delay can be used as a timeout on the
1347  * socket being ready.  The task will be scheduled for execution once
1348  * either the delay has expired or the socket operation is ready.  It
1349  * will be run with the DEFAULT priority.
1350  *
1351  * @param delay when should this operation time out? Use
1352  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1353  * @param priority priority to use for the task
1354  * @param rfd read file-descriptor
1355  * @param task main function of the task
1356  * @param task_cls closure of task
1357  * @return unique task identifier for the job
1358  *         only valid until "task" is started!
1359  */
1360 GNUNET_SCHEDULER_TaskIdentifier
1361 GNUNET_SCHEDULER_add_read_net_with_priority (struct GNUNET_TIME_Relative delay,
1362                                              enum GNUNET_SCHEDULER_Priority priority,
1363                                              struct GNUNET_NETWORK_Handle *rfd,
1364                                              GNUNET_SCHEDULER_Task task, void *task_cls)
1365 {
1366 #if MINGW
1367   struct GNUNET_NETWORK_FDSet *rs;
1368   GNUNET_SCHEDULER_TaskIdentifier ret;
1369
1370   GNUNET_assert (rfd != NULL);
1371   rs = GNUNET_NETWORK_fdset_create ();
1372   GNUNET_NETWORK_fdset_set (rs, rfd);
1373   ret =
1374     GNUNET_SCHEDULER_add_select (priority,
1375                                  delay, rs, NULL,
1376                                  task, task_cls);
1377   GNUNET_NETWORK_fdset_destroy (rs);
1378   return ret;
1379 #else
1380   return add_without_sets (delay, 
1381                            priority,
1382                            GNUNET_NETWORK_get_fd (rfd), -1, task,
1383                            task_cls);
1384 #endif
1385 }
1386
1387
1388
1389 /**
1390  * Schedule a new task to be run with a specified delay or when the
1391  * specified file descriptor is ready for writing.  The delay can be
1392  * used as a timeout on the socket being ready.  The task will be
1393  * scheduled for execution once either the delay has expired or the
1394  * socket operation is ready.  It will be run with the priority of
1395  * the calling task.
1396  *
1397  * @param delay when should this operation time out? Use
1398  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1399  * @param wfd write file-descriptor
1400  * @param task main function of the task
1401  * @param task_cls closure of task
1402  * @return unique task identifier for the job
1403  *         only valid until "task" is started!
1404  */
1405 GNUNET_SCHEDULER_TaskIdentifier
1406 GNUNET_SCHEDULER_add_write_net (struct GNUNET_TIME_Relative delay,
1407                                 struct GNUNET_NETWORK_Handle *wfd,
1408                                 GNUNET_SCHEDULER_Task task, void *task_cls)
1409 {
1410 #if MINGW
1411   struct GNUNET_NETWORK_FDSet *ws;
1412   GNUNET_SCHEDULER_TaskIdentifier ret;
1413
1414   GNUNET_assert (wfd != NULL);
1415   ws = GNUNET_NETWORK_fdset_create ();
1416   GNUNET_NETWORK_fdset_set (ws, wfd);
1417   ret =
1418     GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1419                                  delay, NULL, ws,
1420                                    task, task_cls);
1421   GNUNET_NETWORK_fdset_destroy (ws);
1422   return ret;
1423 #else
1424   GNUNET_assert (GNUNET_NETWORK_get_fd (wfd) >= 0);
1425   return add_without_sets (delay, 
1426                            GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1427                            -1, GNUNET_NETWORK_get_fd (wfd), task,
1428                            task_cls);
1429 #endif
1430 }
1431
1432
1433 /**
1434  * Schedule a new task to be run with a specified delay or when the
1435  * specified file descriptor is ready for reading.  The delay can be
1436  * used as a timeout on the socket being ready.  The task will be
1437  * scheduled for execution once either the delay has expired or the
1438  * socket operation is ready. It will be run with the DEFAULT priority.
1439  *
1440  * @param delay when should this operation time out? Use
1441  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1442  * @param rfd read file-descriptor
1443  * @param task main function of the task
1444  * @param task_cls closure of task
1445  * @return unique task identifier for the job
1446  *         only valid until "task" is started!
1447  */
1448 GNUNET_SCHEDULER_TaskIdentifier
1449 GNUNET_SCHEDULER_add_read_file (struct GNUNET_TIME_Relative delay,
1450                                 const struct GNUNET_DISK_FileHandle *rfd,
1451                                 GNUNET_SCHEDULER_Task task, void *task_cls)
1452 {
1453 #if MINGW
1454   struct GNUNET_NETWORK_FDSet *rs;
1455   GNUNET_SCHEDULER_TaskIdentifier ret;
1456
1457   GNUNET_assert (rfd != NULL);
1458   rs = GNUNET_NETWORK_fdset_create ();
1459   GNUNET_NETWORK_fdset_handle_set (rs, rfd);
1460   ret =
1461       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1462                                    delay, rs, NULL,
1463                                    task, task_cls);
1464   GNUNET_NETWORK_fdset_destroy (rs);
1465   return ret;
1466 #else
1467   int fd;
1468
1469   GNUNET_DISK_internal_file_handle_ (rfd, &fd, sizeof (int));
1470   return add_without_sets (delay, 
1471                            GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1472                            fd, -1, task, task_cls);
1473
1474 #endif
1475 }
1476
1477
1478 /**
1479  * Schedule a new task to be run with a specified delay or when the
1480  * specified file descriptor is ready for writing.  The delay can be
1481  * used as a timeout on the socket being ready.  The task will be
1482  * scheduled for execution once either the delay has expired or the
1483  * socket operation is ready. It will be run with the DEFAULT priority.
1484  *
1485  * @param delay when should this operation time out? Use
1486  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1487  * @param wfd write file-descriptor
1488  * @param task main function of the task
1489  * @param task_cls closure of task
1490  * @return unique task identifier for the job
1491  *         only valid until "task" is started!
1492  */
1493 GNUNET_SCHEDULER_TaskIdentifier
1494 GNUNET_SCHEDULER_add_write_file (struct GNUNET_TIME_Relative delay,
1495                                  const struct GNUNET_DISK_FileHandle *wfd,
1496                                  GNUNET_SCHEDULER_Task task, void *task_cls)
1497 {
1498 #if MINGW
1499   struct GNUNET_NETWORK_FDSet *ws;
1500   GNUNET_SCHEDULER_TaskIdentifier ret;
1501
1502   GNUNET_assert (wfd != NULL);
1503   ws = GNUNET_NETWORK_fdset_create ();
1504   GNUNET_NETWORK_fdset_handle_set (ws, wfd);
1505   ret =
1506       GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1507                                    delay, NULL, ws,
1508                                    task, task_cls);
1509   GNUNET_NETWORK_fdset_destroy (ws);
1510   return ret;
1511 #else
1512   int fd;
1513
1514   GNUNET_DISK_internal_file_handle_ (wfd, &fd, sizeof (int));
1515   GNUNET_assert (fd >= 0);
1516   return add_without_sets (delay, 
1517                            GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1518                            -1, fd, task, task_cls);
1519
1520 #endif
1521 }
1522
1523
1524
1525 /**
1526  * Schedule a new task to be run with a specified delay or when any of
1527  * the specified file descriptor sets is ready.  The delay can be used
1528  * as a timeout on the socket(s) being ready.  The task will be
1529  * scheduled for execution once either the delay has expired or any of
1530  * the socket operations is ready.  This is the most general
1531  * function of the "add" family.  Note that the "prerequisite_task"
1532  * must be satisfied in addition to any of the other conditions.  In
1533  * other words, the task will be started when
1534  * <code>
1535  * (prerequisite-run)
1536  * && (delay-ready
1537  *     || any-rs-ready
1538  *     || any-ws-ready
1539  *     || (shutdown-active && run-on-shutdown) )
1540  * </code>
1541  *
1542  * @param prio how important is this task?
1543  * @param delay how long should we wait? Use GNUNET_TIME_UNIT_FOREVER_REL for "forever",
1544  *        which means that the task will only be run after we receive SIGTERM
1545  * @param rs set of file descriptors we want to read (can be NULL)
1546  * @param ws set of file descriptors we want to write (can be NULL)
1547  * @param task main function of the task
1548  * @param task_cls closure of task
1549  * @return unique task identifier for the job
1550  *         only valid until "task" is started!
1551  */
1552 GNUNET_SCHEDULER_TaskIdentifier
1553 GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio,
1554                              struct GNUNET_TIME_Relative delay,
1555                              const struct GNUNET_NETWORK_FDSet *rs,
1556                              const struct GNUNET_NETWORK_FDSet *ws,
1557                              GNUNET_SCHEDULER_Task task, void *task_cls)
1558 {
1559   struct Task *t;
1560
1561 #if EXECINFO
1562   void *backtrace_array[MAX_TRACE_DEPTH];
1563 #endif
1564
1565   GNUNET_assert (active_task != NULL);
1566   GNUNET_assert (NULL != task);
1567   t = GNUNET_malloc (sizeof (struct Task));
1568   t->callback = task;
1569   t->callback_cls = task_cls;
1570 #if EXECINFO
1571   t->num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
1572   t->backtrace_strings =
1573       backtrace_symbols (backtrace_array, t->num_backtrace_strings);
1574 #endif
1575   t->read_fd = -1;
1576   t->write_fd = -1;
1577   if (rs != NULL)
1578   {
1579     t->read_set = GNUNET_NETWORK_fdset_create ();
1580     GNUNET_NETWORK_fdset_copy (t->read_set, rs);
1581   }
1582   if (ws != NULL)
1583   {
1584     t->write_set = GNUNET_NETWORK_fdset_create ();
1585     GNUNET_NETWORK_fdset_copy (t->write_set, ws);
1586   }
1587   t->id = ++last_id;
1588 #if PROFILE_DELAYS
1589   t->start_time = GNUNET_TIME_absolute_get ();
1590 #endif
1591   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1592   t->priority =
1593       check_priority ((prio ==
1594                        GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority :
1595                       prio);
1596   t->lifeness = current_lifeness;
1597   t->next = pending;
1598   pending = t;
1599   max_priority_added = GNUNET_MAX (max_priority_added, t->priority);
1600   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding task: %llu / %p\n", t->id,
1601        t->callback_cls);
1602 #if EXECINFO
1603   int i;
1604
1605   for (i = 0; i < t->num_backtrace_strings; i++)
1606     LOG (GNUNET_ERROR_TYPE_DEBUG, "Task %llu trace %d: %s\n", t->id, i,
1607          t->backtrace_strings[i]);
1608 #endif
1609   return t->id;
1610 }
1611
1612 /* end of scheduler.c */