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