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