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