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