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