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