use putenv instead of setenv for portability
[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 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
34
35 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
36 #ifdef LINUX
37 #include "execinfo.h"
38
39
40
41 /**
42  * Use lsof to generate file descriptor reports on select error?
43  * (turn off for stable releases).
44  */
45 #define USE_LSOF GNUNET_NO
46
47 /**
48  * Obtain trace information for all scheduler calls that schedule tasks.
49  */
50 #define EXECINFO GNUNET_NO
51
52 /**
53  * Check each file descriptor before adding
54  */
55 #define DEBUG_FDS GNUNET_EXTRA_LOGGING
56
57 /**
58  * Depth of the traces collected via EXECINFO.
59  */
60 #define MAX_TRACE_DEPTH 50
61 #endif
62
63 #define DEBUG_TASKS GNUNET_EXTRA_LOGGING
64
65 /**
66  * Should we figure out which tasks are delayed for a while
67  * before they are run? (Consider using in combination with EXECINFO).
68  */
69 #define PROFILE_DELAYS GNUNET_NO
70
71 /**
72  * Task that were in the queue for longer than this are reported if
73  * PROFILE_DELAYS is active.
74  */
75 #define DELAY_THRESHOLD GNUNET_TIME_UNIT_SECONDS
76
77 /**
78  * Linked list of pending tasks.
79  */
80 struct Task
81 {
82   /**
83    * This is a linked list.
84    */
85   struct Task *next;
86
87   /**
88    * Function to run when ready.
89    */
90   GNUNET_SCHEDULER_Task callback;
91
92   /**
93    * Closure for the callback.
94    */
95   void *callback_cls;
96
97   /**
98    * Set of file descriptors this task is waiting
99    * for for reading.  Once ready, this is updated
100    * to reflect the set of file descriptors ready
101    * for operation.
102    */
103   struct GNUNET_NETWORK_FDSet *read_set;
104
105   /**
106    * Set of file descriptors this task is waiting for for writing.
107    * Once ready, this is updated to reflect the set of file
108    * descriptors ready for operation.
109    */
110   struct GNUNET_NETWORK_FDSet *write_set;
111
112   /**
113    * Unique task identifier.
114    */
115   GNUNET_SCHEDULER_TaskIdentifier id;
116
117   /**
118    * Identifier of a prerequisite task.
119    */
120   GNUNET_SCHEDULER_TaskIdentifier prereq_id;
121
122   /**
123    * Absolute timeout value for the task, or
124    * GNUNET_TIME_UNIT_FOREVER_ABS for "no timeout".
125    */
126   struct GNUNET_TIME_Absolute timeout;
127
128 #if PROFILE_DELAYS
129   /**
130    * When was the task scheduled?
131    */
132   struct GNUNET_TIME_Absolute start_time;
133 #endif
134
135   /**
136    * Why is the task ready?  Set after task is added to ready queue.
137    * Initially set to zero.  All reasons that have already been
138    * satisfied (i.e.  read or write ready) will be set over time.
139    */
140   enum GNUNET_SCHEDULER_Reason reason;
141
142   /**
143    * Task priority.
144    */
145   enum GNUNET_SCHEDULER_Priority priority;
146
147   /**
148    * Set if we only wait for reading from a single FD, otherwise -1.
149    */
150   int read_fd;
151
152   /**
153    * Set if we only wait for writing to a single FD, otherwise -1.
154    */
155   int write_fd;
156
157   /**
158    * Should the existence of this task in the queue be counted as
159    * reason to not shutdown the scheduler?
160    */
161   int lifeness;
162
163 #if EXECINFO
164   /**
165    * Array of strings which make up a backtrace from the point when this
166    * task was scheduled (essentially, who scheduled the task?)
167    */
168   char **backtrace_strings;
169
170   /**
171    * Size of the backtrace_strings array
172    */
173   int num_backtrace_strings;
174 #endif
175
176
177 };
178
179
180 /**
181  * List of tasks waiting for an event.
182  */
183 static struct Task *pending;
184
185 /**
186  * List of tasks waiting ONLY for a timeout event.
187  * Sorted by timeout (earliest first).  Used so that
188  * we do not traverse the list of these tasks when
189  * building select sets (we just look at the head
190  * to determine the respective timeout ONCE).
191  */
192 static struct Task *pending_timeout;
193
194 /**
195  * Last inserted task waiting ONLY for a timeout event.
196  * Used to (heuristically) speed up insertion.
197  */
198 static struct Task *pending_timeout_last;
199
200 /**
201  * ID of the task that is running right now.
202  */
203 static struct Task *active_task;
204
205 /**
206  * List of tasks ready to run right now,
207  * grouped by importance.
208  */
209 static struct Task *ready[GNUNET_SCHEDULER_PRIORITY_COUNT];
210
211 /**
212  * Identity of the last task queued.  Incremented for each task to
213  * generate a unique task ID (it is virtually impossible to start
214  * more than 2^64 tasks during the lifetime of a process).
215  */
216 static GNUNET_SCHEDULER_TaskIdentifier last_id;
217
218 /**
219  * Highest number so that all tasks with smaller identifiers
220  * have already completed.  Also the lowest number of a task
221  * still waiting to be executed.
222  */
223 static GNUNET_SCHEDULER_TaskIdentifier lowest_pending_id;
224
225 /**
226  * Number of tasks on the ready list.
227  */
228 static unsigned int ready_count;
229
230 /**
231  * How many tasks have we run so far?
232  */
233 static unsigned long long tasks_run;
234
235 /**
236  * Priority of the task running right now.  Only
237  * valid while a task is running.
238  */
239 static enum GNUNET_SCHEDULER_Priority current_priority;
240
241 /**
242  * Priority of the highest task added in the current select
243  * iteration.
244  */
245 static enum GNUNET_SCHEDULER_Priority max_priority_added;
246
247 /**
248  * Value of the 'lifeness' flag for the current task.
249  */
250 static int current_lifeness;
251
252 /**
253  * Function to use as a select() in the scheduler.
254  * If NULL, we use GNUNET_NETWORK_socket_select ().
255  */
256 static GNUNET_SCHEDULER_select scheduler_select;
257
258 /**
259  * Closure for 'scheduler_select'.
260  */
261 static void *scheduler_select_cls;
262
263 /**
264  * Sets the select function to use in the scheduler (scheduler_select).
265  *
266  * @param new_select new select function to use
267  * @param new_select_cls closure for 'new_select'
268  * @return previously used select function, NULL for default
269  */
270 void
271 GNUNET_SCHEDULER_set_select (GNUNET_SCHEDULER_select new_select,
272                              void *new_select_cls)
273 {
274   scheduler_select = new_select;
275   scheduler_select_cls = new_select_cls;
276 }
277
278
279 /**
280  * Check that the given priority is legal (and return it).
281  *
282  * @param p priority value to check
283  * @return p on success, 0 on error
284  */
285 static enum GNUNET_SCHEDULER_Priority
286 check_priority (enum GNUNET_SCHEDULER_Priority p)
287 {
288   if ((p >= 0) && (p < GNUNET_SCHEDULER_PRIORITY_COUNT))
289     return p;
290   GNUNET_assert (0);
291   return 0;                     /* make compiler happy */
292 }
293
294
295 /**
296  * Is a task with this identifier still pending?  Also updates
297  * "lowest_pending_id" as a side-effect (for faster checks in the
298  * future), but only if the return value is "GNUNET_NO" (and
299  * the "lowest_pending_id" check failed).
300  *
301  * @param id which task are we checking for
302  * @return GNUNET_YES if so, GNUNET_NO if not
303  */
304 static int
305 is_pending (GNUNET_SCHEDULER_TaskIdentifier id)
306 {
307   struct Task *pos;
308   enum GNUNET_SCHEDULER_Priority p;
309   GNUNET_SCHEDULER_TaskIdentifier min;
310
311   if (id < lowest_pending_id)
312     return GNUNET_NO;
313   min = -1;                     /* maximum value */
314   pos = pending;
315   while (pos != NULL)
316   {
317     if (pos->id == id)
318       return GNUNET_YES;
319     if (pos->id < min)
320       min = pos->id;
321     pos = pos->next;
322   }
323   pos = pending_timeout;
324   while (pos != NULL)
325   {
326     if (pos->id == id)
327       return GNUNET_YES;
328     if (pos->id < min)
329       min = pos->id;
330     pos = pos->next;
331   }
332   for (p = 0; p < GNUNET_SCHEDULER_PRIORITY_COUNT; p++)
333   {
334     pos = ready[p];
335     while (pos != NULL)
336     {
337       if (pos->id == id)
338         return GNUNET_YES;
339       if (pos->id < min)
340         min = pos->id;
341       pos = pos->next;
342     }
343   }
344   lowest_pending_id = min;
345   return GNUNET_NO;
346 }
347
348
349 /**
350  * Update all sets and timeout for select.
351  *
352  * @param rs read-set, set to all FDs we would like to read (updated)
353  * @param ws write-set, set to all FDs we would like to write (updated)
354  * @param timeout next timeout (updated)
355  */
356 static void
357 update_sets (struct GNUNET_NETWORK_FDSet *rs, struct GNUNET_NETWORK_FDSet *ws,
358              struct GNUNET_TIME_Relative *timeout)
359 {
360   struct Task *pos;
361   struct GNUNET_TIME_Absolute now;
362   struct GNUNET_TIME_Relative to;
363
364   now = GNUNET_TIME_absolute_get ();
365   pos = pending_timeout;
366   if (pos != NULL)
367   {
368     to = GNUNET_TIME_absolute_get_difference (now, pos->timeout);
369     if (timeout->rel_value > to.rel_value)
370       *timeout = to;
371     if (pos->reason != 0)
372       *timeout = GNUNET_TIME_UNIT_ZERO;
373   }
374   pos = pending;
375   while (pos != NULL)
376   {
377     if ((pos->prereq_id != GNUNET_SCHEDULER_NO_TASK) &&
378         (GNUNET_YES == is_pending (pos->prereq_id)))
379     {
380       pos = pos->next;
381       continue;
382     }
383     if (pos->timeout.abs_value != GNUNET_TIME_UNIT_FOREVER_ABS.abs_value)
384     {
385       to = GNUNET_TIME_absolute_get_difference (now, pos->timeout);
386       if (timeout->rel_value > to.rel_value)
387         *timeout = to;
388     }
389     if (pos->read_fd != -1)
390       GNUNET_NETWORK_fdset_set_native (rs, pos->read_fd);
391     if (pos->write_fd != -1)
392       GNUNET_NETWORK_fdset_set_native (ws, pos->write_fd);
393     if (pos->read_set != NULL)
394       GNUNET_NETWORK_fdset_add (rs, pos->read_set);
395     if (pos->write_set != NULL)
396       GNUNET_NETWORK_fdset_add (ws, pos->write_set);
397     if (pos->reason != 0)
398       *timeout = GNUNET_TIME_UNIT_ZERO;
399     pos = pos->next;
400   }
401 }
402
403
404 /**
405  * Check if the ready set overlaps with the set we want to have ready.
406  * If so, update the want set (set all FDs that are ready).  If not,
407  * return GNUNET_NO.
408  *
409  * @param ready set that is ready
410  * @param want set that we want to be ready
411  * @return GNUNET_YES if there was some overlap
412  */
413 static int
414 set_overlaps (const struct GNUNET_NETWORK_FDSet *ready,
415               struct GNUNET_NETWORK_FDSet *want)
416 {
417   if ((NULL == want) || (NULL == ready))
418     return GNUNET_NO;
419   if (GNUNET_NETWORK_fdset_overlap (ready, want))
420   {
421     /* copy all over (yes, there maybe unrelated bits,
422      * but this should not hurt well-written clients) */
423     GNUNET_NETWORK_fdset_copy (want, ready);
424     return GNUNET_YES;
425   }
426   return GNUNET_NO;
427 }
428
429
430 /**
431  * Check if the given task is eligible to run now.
432  * Also set the reason why it is eligible.
433  *
434  * @param task task to check if it is ready
435  * @param now the current time
436  * @param rs set of FDs ready for reading
437  * @param ws set of FDs ready for writing
438  * @return GNUNET_YES if we can run it, GNUNET_NO if not.
439  */
440 static int
441 is_ready (struct Task *task, struct GNUNET_TIME_Absolute now,
442           const struct GNUNET_NETWORK_FDSet *rs,
443           const struct GNUNET_NETWORK_FDSet *ws)
444 {
445   enum GNUNET_SCHEDULER_Reason reason;
446
447   reason = task->reason;
448   if (now.abs_value >= task->timeout.abs_value)
449     reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
450   if ((0 == (reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
451       (((task->read_fd != -1) &&
452         (GNUNET_YES == GNUNET_NETWORK_fdset_test_native (rs, task->read_fd))) ||
453        (set_overlaps (rs, task->read_set))))
454     reason |= GNUNET_SCHEDULER_REASON_READ_READY;
455   if ((0 == (reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) &&
456       (((task->write_fd != -1) &&
457         (GNUNET_YES == GNUNET_NETWORK_fdset_test_native (ws, task->write_fd)))
458        || (set_overlaps (ws, task->write_set))))
459     reason |= GNUNET_SCHEDULER_REASON_WRITE_READY;
460   if (reason == 0)
461     return GNUNET_NO;           /* not ready */
462   if (task->prereq_id != GNUNET_SCHEDULER_NO_TASK)
463   {
464     if (GNUNET_YES == is_pending (task->prereq_id))
465     {
466       task->reason = reason;
467       return GNUNET_NO;         /* prereq waiting */
468     }
469     reason |= GNUNET_SCHEDULER_REASON_PREREQ_DONE;
470   }
471   task->reason = reason;
472   return GNUNET_YES;
473 }
474
475
476 /**
477  * Put a task that is ready for execution into the ready queue.
478  *
479  * @param task task ready for execution
480  */
481 static void
482 queue_ready_task (struct Task *task)
483 {
484   enum GNUNET_SCHEDULER_Priority p = task->priority;
485
486   if (0 != (task->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
487     p = GNUNET_SCHEDULER_PRIORITY_SHUTDOWN;
488   task->next = ready[check_priority (p)];
489   ready[check_priority (p)] = task;
490   ready_count++;
491 }
492
493
494 /**
495  * Check which tasks are ready and move them
496  * to the respective ready queue.
497  *
498  * @param rs FDs ready for reading
499  * @param ws FDs ready for writing
500  */
501 static void
502 check_ready (const struct GNUNET_NETWORK_FDSet *rs,
503              const struct GNUNET_NETWORK_FDSet *ws)
504 {
505   struct Task *pos;
506   struct Task *prev;
507   struct Task *next;
508   struct GNUNET_TIME_Absolute now;
509
510   now = GNUNET_TIME_absolute_get ();
511   prev = NULL;
512   pos = pending_timeout;
513   while (pos != NULL)
514   {
515     next = pos->next;
516     if (now.abs_value >= pos->timeout.abs_value)
517       pos->reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
518     if (0 == pos->reason)
519       break;
520     pending_timeout = next;
521     if (pending_timeout_last == pos)
522       pending_timeout_last = NULL;
523     queue_ready_task (pos);
524     pos = next;
525   }
526   pos = pending;
527   while (pos != NULL)
528   {
529 #if DEBUG_TASKS
530     LOG (GNUNET_ERROR_TYPE_DEBUG, "Checking readiness of task: %llu / %p\n",
531          pos->id, pos->callback_cls);
532 #endif
533     next = pos->next;
534     if (GNUNET_YES == is_ready (pos, now, rs, ws))
535     {
536       if (prev == NULL)
537         pending = next;
538       else
539         prev->next = next;
540       queue_ready_task (pos);
541       pos = next;
542       continue;
543     }
544     prev = pos;
545     pos = next;
546   }
547 }
548
549
550 /**
551  * Request the shutdown of a scheduler.  Marks all currently
552  * pending tasks as ready because of shutdown.  This will
553  * cause all tasks to run (as soon as possible, respecting
554  * priorities and prerequisite tasks).  Note that tasks
555  * scheduled AFTER this call may still be delayed arbitrarily.
556  */
557 void
558 GNUNET_SCHEDULER_shutdown ()
559 {
560   struct Task *pos;
561   int i;
562
563   pos = pending_timeout;
564   while (pos != NULL)
565   {
566     pos->reason |= GNUNET_SCHEDULER_REASON_SHUTDOWN;
567     /* we don't move the task into the ready queue yet; check_ready
568      * will do that later, possibly adding additional
569      * readiness-factors */
570     pos = pos->next;
571   }
572   pos = pending;
573   while (pos != NULL)
574   {
575     pos->reason |= GNUNET_SCHEDULER_REASON_SHUTDOWN;
576     /* we don't move the task into the ready queue yet; check_ready
577      * will do that later, possibly adding additional
578      * readiness-factors */
579     pos = pos->next;
580   }
581   for (i = 0; i < GNUNET_SCHEDULER_PRIORITY_COUNT; i++)
582   {
583     pos = ready[i];
584     while (pos != NULL)
585     {
586       pos->reason |= GNUNET_SCHEDULER_REASON_SHUTDOWN;
587       /* we don't move the task into the ready queue yet; check_ready
588        * will do that later, possibly adding additional
589        * readiness-factors */
590       pos = pos->next;
591     }
592   }
593 }
594
595
596 /**
597  * Destroy a task (release associated resources)
598  *
599  * @param t task to destroy
600  */
601 static void
602 destroy_task (struct Task *t)
603 {
604   if (NULL != t->read_set)
605     GNUNET_NETWORK_fdset_destroy (t->read_set);
606   if (NULL != t->write_set)
607     GNUNET_NETWORK_fdset_destroy (t->write_set);
608 #if EXECINFO
609   GNUNET_free (t->backtrace_strings);
610 #endif
611   GNUNET_free (t);
612 }
613
614
615 /**
616  * Run at least one task in the highest-priority queue that is not
617  * empty.  Keep running tasks until we are either no longer running
618  * "URGENT" tasks or until we have at least one "pending" task (which
619  * may become ready, hence we should select on it).  Naturally, if
620  * there are no more ready tasks, we also return.
621  *
622  * @param rs FDs ready for reading
623  * @param ws FDs ready for writing
624  */
625 static void
626 run_ready (struct GNUNET_NETWORK_FDSet *rs, struct GNUNET_NETWORK_FDSet *ws)
627 {
628   enum GNUNET_SCHEDULER_Priority p;
629   struct Task *pos;
630   struct GNUNET_SCHEDULER_TaskContext tc;
631
632   max_priority_added = GNUNET_SCHEDULER_PRIORITY_KEEP;
633   do
634   {
635     if (ready_count == 0)
636       return;
637     GNUNET_assert (ready[GNUNET_SCHEDULER_PRIORITY_KEEP] == NULL);
638     /* yes, p>0 is correct, 0 is "KEEP" which should
639      * always be an empty queue (see assertion)! */
640     for (p = GNUNET_SCHEDULER_PRIORITY_COUNT - 1; p > 0; p--)
641     {
642       pos = ready[p];
643       if (pos != NULL)
644         break;
645     }
646     GNUNET_assert (pos != NULL);        /* ready_count wrong? */
647     ready[p] = pos->next;
648     ready_count--;
649     if (current_priority != pos->priority)
650     {
651       current_priority = pos->priority;
652       (void) GNUNET_OS_set_process_priority (GNUNET_OS_process_current (),
653                                              pos->priority);
654     }
655     current_lifeness = pos->lifeness;
656     active_task = pos;
657 #if PROFILE_DELAYS
658     if (GNUNET_TIME_absolute_get_duration (pos->start_time).rel_value >
659         DELAY_THRESHOLD.rel_value)
660     {
661       LOG (GNUNET_ERROR_TYPE_ERROR, "Task %llu took %llums to be scheduled\n",
662            pos->id,
663            (unsigned long long)
664            GNUNET_TIME_absolute_get_duration (pos->start_time).rel_value);
665     }
666 #endif
667     tc.reason = pos->reason;
668     tc.read_ready = (pos->read_set == NULL) ? rs : pos->read_set;
669     if ((pos->read_fd != -1) &&
670         (0 != (pos->reason & GNUNET_SCHEDULER_REASON_READ_READY)))
671       GNUNET_NETWORK_fdset_set_native (rs, pos->read_fd);
672     tc.write_ready = (pos->write_set == NULL) ? ws : pos->write_set;
673     if ((pos->write_fd != -1) &&
674         (0 != (pos->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)))
675       GNUNET_NETWORK_fdset_set_native (ws, pos->write_fd);
676     if (((tc.reason & GNUNET_SCHEDULER_REASON_WRITE_READY) != 0) &&
677         (pos->write_fd != -1) &&
678         (!GNUNET_NETWORK_fdset_test_native (ws, pos->write_fd)))
679       abort ();                 // added to ready in previous select loop!
680 #if DEBUG_TASKS
681     LOG (GNUNET_ERROR_TYPE_DEBUG, "Running task: %llu / %p\n", pos->id,
682          pos->callback_cls);
683 #endif
684     pos->callback (pos->callback_cls, &tc);
685 #if EXECINFO
686     int i;
687
688     for (i = 0; i < pos->num_backtrace_strings; i++)
689       LOG (GNUNET_ERROR_TYPE_ERROR, "Task %llu trace %d: %s\n", pos->id, i,
690            pos->backtrace_strings[i]);
691 #endif
692     active_task = NULL;
693     destroy_task (pos);
694     tasks_run++;
695   }
696   while ((pending == NULL) || (p >= max_priority_added));
697 }
698
699 /**
700  * Pipe used to communicate shutdown via signal.
701  */
702 static struct GNUNET_DISK_PipeHandle *shutdown_pipe_handle;
703
704 /**
705  * Signal handler called for SIGPIPE.
706  */
707 #ifndef MINGW
708 static void
709 sighandler_pipe ()
710 {
711   return;
712 }
713 #endif
714 /**
715  * Signal handler called for signals that should cause us to shutdown.
716  */
717 static void
718 sighandler_shutdown ()
719 {
720   static char c;
721   int old_errno = errno;        /* backup errno */
722
723   GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle
724                           (shutdown_pipe_handle, GNUNET_DISK_PIPE_END_WRITE),
725                           &c, sizeof (c));
726   errno = old_errno;
727 }
728
729
730 /**
731  * Check if the system is still life. Trigger shutdown if we
732  * have tasks, but none of them give us lifeness.
733  *
734  * @return GNUNET_OK to continue the main loop,
735  *         GNUNET_NO to exit
736  */
737 static int
738 check_lifeness ()
739 {
740   struct Task *t;
741
742   if (ready_count > 0)
743     return GNUNET_OK;
744   for (t = pending; NULL != t; t = t->next)
745     if (t->lifeness == GNUNET_YES)
746       return GNUNET_OK;
747   for (t = pending_timeout; NULL != t; t = t->next)
748     if (t->lifeness == GNUNET_YES)
749       return GNUNET_OK;
750   if ((NULL != pending) || (NULL != pending_timeout))
751   {
752     GNUNET_SCHEDULER_shutdown ();
753     return GNUNET_OK;
754   }
755   return GNUNET_NO;
756 }
757
758
759 /**
760  * Initialize and run scheduler.  This function will return when all
761  * tasks have completed.  On systems with signals, receiving a SIGTERM
762  * (and other similar signals) will cause "GNUNET_SCHEDULER_shutdown"
763  * to be run after the active task is complete.  As a result, SIGTERM
764  * causes all active tasks to be scheduled with reason
765  * "GNUNET_SCHEDULER_REASON_SHUTDOWN".  (However, tasks added
766  * afterwards will execute normally!). Note that any particular signal
767  * will only shut down one scheduler; applications should always only
768  * create a single scheduler.
769  *
770  * @param task task to run immediately
771  * @param task_cls closure of task
772  */
773 void
774 GNUNET_SCHEDULER_run (GNUNET_SCHEDULER_Task task, void *task_cls)
775 {
776   struct GNUNET_NETWORK_FDSet *rs;
777   struct GNUNET_NETWORK_FDSet *ws;
778   struct GNUNET_TIME_Relative timeout;
779   int ret;
780   struct GNUNET_SIGNAL_Context *shc_int;
781   struct GNUNET_SIGNAL_Context *shc_term;
782
783 #ifndef MINGW
784   struct GNUNET_SIGNAL_Context *shc_quit;
785   struct GNUNET_SIGNAL_Context *shc_hup;
786   struct GNUNET_SIGNAL_Context *shc_pipe;
787 #endif
788   unsigned long long last_tr;
789   unsigned int busy_wait_warning;
790   const struct GNUNET_DISK_FileHandle *pr;
791   char c;
792
793   GNUNET_assert (active_task == NULL);
794   rs = GNUNET_NETWORK_fdset_create ();
795   ws = GNUNET_NETWORK_fdset_create ();
796   GNUNET_assert (shutdown_pipe_handle == NULL);
797   shutdown_pipe_handle = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO);
798   GNUNET_assert (shutdown_pipe_handle != NULL);
799   pr = GNUNET_DISK_pipe_handle (shutdown_pipe_handle,
800                                 GNUNET_DISK_PIPE_END_READ);
801   GNUNET_assert (pr != NULL);
802   shc_int = GNUNET_SIGNAL_handler_install (SIGINT, &sighandler_shutdown);
803   shc_term = GNUNET_SIGNAL_handler_install (SIGTERM, &sighandler_shutdown);
804 #ifndef MINGW
805   shc_pipe = GNUNET_SIGNAL_handler_install (SIGPIPE, &sighandler_pipe);
806   shc_quit = GNUNET_SIGNAL_handler_install (SIGQUIT, &sighandler_shutdown);
807   shc_hup = GNUNET_SIGNAL_handler_install (SIGHUP, &sighandler_shutdown);
808 #endif
809   current_priority = GNUNET_SCHEDULER_PRIORITY_DEFAULT;
810   current_lifeness = GNUNET_YES;
811   GNUNET_SCHEDULER_add_continuation (task, task_cls,
812                                      GNUNET_SCHEDULER_REASON_STARTUP);
813 #if ENABLE_WINDOWS_WORKAROUNDS
814   active_task = (void *) (long) -1;     /* force passing of sanity check */
815   GNUNET_SCHEDULER_add_now_with_lifeness (GNUNET_NO,
816                                           &GNUNET_OS_install_parent_control_handler,
817                                           NULL);
818   active_task = NULL;
819 #endif
820   last_tr = 0;
821   busy_wait_warning = 0;
822   while (GNUNET_OK == check_lifeness ())
823   {
824     GNUNET_NETWORK_fdset_zero (rs);
825     GNUNET_NETWORK_fdset_zero (ws);
826     timeout = GNUNET_TIME_UNIT_FOREVER_REL;
827     update_sets (rs, ws, &timeout);
828     GNUNET_NETWORK_fdset_handle_set (rs, pr);
829     if (ready_count > 0)
830     {
831       /* no blocking, more work already ready! */
832       timeout = GNUNET_TIME_UNIT_ZERO;
833     }
834     if (NULL == scheduler_select)
835       ret = GNUNET_NETWORK_socket_select (rs, ws, NULL, timeout);
836     else
837       ret = scheduler_select (scheduler_select_cls, rs, ws, NULL, timeout);
838     if (ret == GNUNET_SYSERR)
839     {
840       if (errno == EINTR)
841         continue;
842
843       LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "select");
844 #ifndef MINGW
845 #if USE_LSOF
846       char lsof[512];
847
848       snprintf (lsof, sizeof (lsof), "lsof -p %d", getpid ());
849       (void) close (1);
850       (void) dup2 (2, 1);
851       if (0 != system (lsof))
852         LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "system");
853 #endif
854 #endif
855       abort ();
856       break;
857     }
858     if ((ret == 0) && (timeout.rel_value == 0) && (busy_wait_warning > 16))
859     {
860       LOG (GNUNET_ERROR_TYPE_WARNING, _("Looks like we're busy waiting...\n"));
861       sleep (1);                /* mitigate */
862     }
863     check_ready (rs, ws);
864     run_ready (rs, ws);
865     if (GNUNET_NETWORK_fdset_handle_isset (rs, pr))
866     {
867       /* consume the signal */
868       GNUNET_DISK_file_read (pr, &c, sizeof (c));
869       /* mark all active tasks as ready due to shutdown */
870       GNUNET_SCHEDULER_shutdown ();
871     }
872     if (last_tr == tasks_run)
873     {
874       busy_wait_warning++;
875     }
876     else
877     {
878       last_tr = tasks_run;
879       busy_wait_warning = 0;
880     }
881   }
882   GNUNET_SIGNAL_handler_uninstall (shc_int);
883   GNUNET_SIGNAL_handler_uninstall (shc_term);
884 #ifndef MINGW
885   GNUNET_SIGNAL_handler_uninstall (shc_pipe);
886   GNUNET_SIGNAL_handler_uninstall (shc_quit);
887   GNUNET_SIGNAL_handler_uninstall (shc_hup);
888 #endif
889   GNUNET_DISK_pipe_close (shutdown_pipe_handle);
890   shutdown_pipe_handle = NULL;
891   GNUNET_NETWORK_fdset_destroy (rs);
892   GNUNET_NETWORK_fdset_destroy (ws);
893 }
894
895
896 /**
897  * Obtain the reason code for why the current task was
898  * started.  Will return the same value as
899  * the GNUNET_SCHEDULER_TaskContext's reason field.
900  *
901  * @return reason(s) why the current task is run
902  */
903 enum GNUNET_SCHEDULER_Reason
904 GNUNET_SCHEDULER_get_reason ()
905 {
906   GNUNET_assert (active_task != NULL);
907   return active_task->reason;
908 }
909
910
911 /**
912  * Get information about the current load of this scheduler.  Use this
913  * function to determine if an elective task should be added or simply
914  * dropped (if the decision should be made based on the number of
915  * tasks ready to run).
916  *
917  * @param p priority level to look at
918  * @return number of tasks pending right now
919  */
920 unsigned int
921 GNUNET_SCHEDULER_get_load (enum GNUNET_SCHEDULER_Priority p)
922 {
923   struct Task *pos;
924   unsigned int ret;
925
926   GNUNET_assert (active_task != NULL);
927   if (p == GNUNET_SCHEDULER_PRIORITY_COUNT)
928     return ready_count;
929   if (p == GNUNET_SCHEDULER_PRIORITY_KEEP)
930     p = current_priority;
931   ret = 0;
932   pos = ready[check_priority (p)];
933   while (pos != NULL)
934   {
935     pos = pos->next;
936     ret++;
937   }
938   return ret;
939 }
940
941
942 /**
943  * Cancel the task with the specified identifier.
944  * The task must not yet have run.
945  *
946  * @param task id of the task to cancel
947  * @return original closure of the task
948  */
949 void *
950 GNUNET_SCHEDULER_cancel (GNUNET_SCHEDULER_TaskIdentifier task)
951 {
952   struct Task *t;
953   struct Task *prev;
954   enum GNUNET_SCHEDULER_Priority p;
955   int to;
956   void *ret;
957
958   GNUNET_assert (active_task != NULL);
959   to = 0;
960   prev = NULL;
961   t = pending;
962   while (t != NULL)
963   {
964     if (t->id == task)
965       break;
966     prev = t;
967     t = t->next;
968   }
969   if (t == NULL)
970   {
971     prev = NULL;
972     to = 1;
973     t = pending_timeout;
974     while (t != NULL)
975     {
976       if (t->id == task)
977         break;
978       prev = t;
979       t = t->next;
980     }
981     if (pending_timeout_last == t)
982       pending_timeout_last = NULL;
983   }
984   p = 0;
985   while (t == NULL)
986   {
987     p++;
988     if (p >= GNUNET_SCHEDULER_PRIORITY_COUNT)
989     {
990       LOG (GNUNET_ERROR_TYPE_ERROR, _("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   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   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding continuation task: %llu / %p\n", t->id,
1080        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   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     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       LOG (GNUNET_ERROR_TYPE_ERROR, "Got invalid file descriptor %d!\n", rfd);
1339 #if EXECINFO
1340       int i;
1341
1342       for (i = 0; i < t->num_backtrace_strings; i++)
1343         LOG (GNUNET_ERROR_TYPE_DEBUG, "Trace: %s\n", t->backtrace_strings[i]);
1344 #endif
1345       GNUNET_assert (0);
1346     }
1347   }
1348   if (-1 != wfd)
1349   {
1350     int flags = fcntl (wfd, F_GETFD);
1351
1352     if (flags == -1 && errno == EBADF)
1353     {
1354       LOG (GNUNET_ERROR_TYPE_ERROR, "Got invalid file descriptor %d!\n", wfd);
1355 #if EXECINFO
1356       int i;
1357
1358       for (i = 0; i < t->num_backtrace_strings; i++)
1359         LOG (GNUNET_ERROR_TYPE_DEBUG, "Trace: %s\n", t->backtrace_strings[i]);
1360 #endif
1361       GNUNET_assert (0);
1362     }
1363   }
1364 #endif
1365   t->read_fd = rfd;
1366   GNUNET_assert (wfd >= -1);
1367   t->write_fd = wfd;
1368   t->id = ++last_id;
1369 #if PROFILE_DELAYS
1370   t->start_time = GNUNET_TIME_absolute_get ();
1371 #endif
1372   t->prereq_id = GNUNET_SCHEDULER_NO_TASK;
1373   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1374   t->priority = check_priority (current_priority);
1375   t->lifeness = current_lifeness;
1376   t->next = pending;
1377   pending = t;
1378   max_priority_added = GNUNET_MAX (max_priority_added, t->priority);
1379 #if DEBUG_TASKS
1380   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding task: %llu / %p\n", t->id,
1381        t->callback_cls);
1382 #endif
1383 #if EXECINFO
1384   int i;
1385
1386   for (i = 0; i < t->num_backtrace_strings; i++)
1387     LOG (GNUNET_ERROR_TYPE_DEBUG, "Task %llu trace %d: %s\n", t->id, i,
1388          t->backtrace_strings[i]);
1389 #endif
1390   return t->id;
1391 }
1392 #endif
1393
1394
1395
1396 /**
1397  * Schedule a new task to be run with a specified delay or when the
1398  * specified file descriptor is ready for reading.  The delay can be
1399  * used as a timeout on the socket being ready.  The task will be
1400  * scheduled for execution once either the delay has expired or the
1401  * socket operation is ready.  It will be run with the priority of
1402  * the calling task.
1403  *
1404  * @param delay when should this operation time out? Use
1405  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1406  * @param rfd read file-descriptor
1407  * @param task main function of the task
1408  * @param task_cls closure of task
1409  * @return unique task identifier for the job
1410  *         only valid until "task" is started!
1411  */
1412 GNUNET_SCHEDULER_TaskIdentifier
1413 GNUNET_SCHEDULER_add_read_net (struct GNUNET_TIME_Relative delay,
1414                                struct GNUNET_NETWORK_Handle *rfd,
1415                                GNUNET_SCHEDULER_Task task, void *task_cls)
1416 {
1417 #if MINGW
1418   struct GNUNET_NETWORK_FDSet *rs;
1419   GNUNET_SCHEDULER_TaskIdentifier ret;
1420
1421   GNUNET_assert (rfd != NULL);
1422   rs = GNUNET_NETWORK_fdset_create ();
1423   GNUNET_NETWORK_fdset_set (rs, rfd);
1424   ret =
1425       GNUNET_SCHEDULER_add_select (check_priority (current_priority),
1426                                    GNUNET_SCHEDULER_NO_TASK, delay, rs, NULL,
1427                                    task, task_cls);
1428   GNUNET_NETWORK_fdset_destroy (rs);
1429   return ret;
1430 #else
1431   return add_without_sets (delay, GNUNET_NETWORK_get_fd (rfd), -1, task,
1432                            task_cls);
1433 #endif
1434 }
1435
1436
1437 /**
1438  * Schedule a new task to be run with a specified delay or when the
1439  * specified file descriptor is ready for writing.  The delay can be
1440  * used as a timeout on the socket being ready.  The task will be
1441  * scheduled for execution once either the delay has expired or the
1442  * socket operation is ready.  It will be run with the priority of
1443  * the calling task.
1444  *
1445  * @param delay when should this operation time out? Use
1446  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1447  * @param wfd write file-descriptor
1448  * @param task main function of the task
1449  * @param task_cls closure of task
1450  * @return unique task identifier for the job
1451  *         only valid until "task" is started!
1452  */
1453 GNUNET_SCHEDULER_TaskIdentifier
1454 GNUNET_SCHEDULER_add_write_net (struct GNUNET_TIME_Relative delay,
1455                                 struct GNUNET_NETWORK_Handle *wfd,
1456                                 GNUNET_SCHEDULER_Task task, void *task_cls)
1457 {
1458 #if MINGW
1459   struct GNUNET_NETWORK_FDSet *ws;
1460   GNUNET_SCHEDULER_TaskIdentifier ret;
1461
1462   GNUNET_assert (wfd != NULL);
1463   ws = GNUNET_NETWORK_fdset_create ();
1464   GNUNET_NETWORK_fdset_set (ws, wfd);
1465   ret =
1466       GNUNET_SCHEDULER_add_select (check_priority (current_priority),
1467                                    GNUNET_SCHEDULER_NO_TASK, delay, NULL, ws,
1468                                    task, task_cls);
1469   GNUNET_NETWORK_fdset_destroy (ws);
1470   return ret;
1471 #else
1472   GNUNET_assert (GNUNET_NETWORK_get_fd (wfd) >= 0);
1473   return add_without_sets (delay, -1, GNUNET_NETWORK_get_fd (wfd), task,
1474                            task_cls);
1475 #endif
1476 }
1477
1478
1479 /**
1480  * Schedule a new task to be run with a specified delay or when the
1481  * specified file descriptor is ready for reading.  The delay can be
1482  * used as a timeout on the socket being ready.  The task will be
1483  * scheduled for execution once either the delay has expired or the
1484  * socket operation is ready. It will be run with the priority of
1485  * the calling task.
1486  *
1487  * @param delay when should this operation time out? Use
1488  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1489  * @param rfd read file-descriptor
1490  * @param task main function of the task
1491  * @param task_cls closure of task
1492  * @return unique task identifier for the job
1493  *         only valid until "task" is started!
1494  */
1495 GNUNET_SCHEDULER_TaskIdentifier
1496 GNUNET_SCHEDULER_add_read_file (struct GNUNET_TIME_Relative delay,
1497                                 const struct GNUNET_DISK_FileHandle *rfd,
1498                                 GNUNET_SCHEDULER_Task task, void *task_cls)
1499 {
1500 #if MINGW
1501   struct GNUNET_NETWORK_FDSet *rs;
1502   GNUNET_SCHEDULER_TaskIdentifier ret;
1503
1504   GNUNET_assert (rfd != NULL);
1505   rs = GNUNET_NETWORK_fdset_create ();
1506   GNUNET_NETWORK_fdset_handle_set (rs, rfd);
1507   ret =
1508       GNUNET_SCHEDULER_add_select (check_priority (current_priority),
1509                                    GNUNET_SCHEDULER_NO_TASK, delay, rs, NULL,
1510                                    task, task_cls);
1511   GNUNET_NETWORK_fdset_destroy (rs);
1512   return ret;
1513 #else
1514   int fd;
1515
1516   GNUNET_DISK_internal_file_handle_ (rfd, &fd, sizeof (int));
1517   return add_without_sets (delay, fd, -1, task, task_cls);
1518
1519 #endif
1520 }
1521
1522
1523 /**
1524  * Schedule a new task to be run with a specified delay or when the
1525  * specified file descriptor is ready for writing.  The delay can be
1526  * used as a timeout on the socket being ready.  The task will be
1527  * scheduled for execution once either the delay has expired or the
1528  * socket operation is ready. It will be run with the priority of
1529  * the calling task.
1530  *
1531  * @param delay when should this operation time out? Use
1532  *        GNUNET_TIME_UNIT_FOREVER_REL for "on shutdown"
1533  * @param wfd write file-descriptor
1534  * @param task main function of the task
1535  * @param task_cls closure of task
1536  * @return unique task identifier for the job
1537  *         only valid until "task" is started!
1538  */
1539 GNUNET_SCHEDULER_TaskIdentifier
1540 GNUNET_SCHEDULER_add_write_file (struct GNUNET_TIME_Relative delay,
1541                                  const struct GNUNET_DISK_FileHandle *wfd,
1542                                  GNUNET_SCHEDULER_Task task, void *task_cls)
1543 {
1544 #if MINGW
1545   struct GNUNET_NETWORK_FDSet *ws;
1546   GNUNET_SCHEDULER_TaskIdentifier ret;
1547
1548   GNUNET_assert (wfd != NULL);
1549   ws = GNUNET_NETWORK_fdset_create ();
1550   GNUNET_NETWORK_fdset_handle_set (ws, wfd);
1551   ret =
1552       GNUNET_SCHEDULER_add_select (check_priority (current_priority),
1553                                    GNUNET_SCHEDULER_NO_TASK, delay, NULL, ws,
1554                                    task, task_cls);
1555   GNUNET_NETWORK_fdset_destroy (ws);
1556   return ret;
1557 #else
1558   int fd;
1559
1560   GNUNET_DISK_internal_file_handle_ (wfd, &fd, sizeof (int));
1561   GNUNET_assert (fd >= 0);
1562   return add_without_sets (delay, -1, fd, task, task_cls);
1563
1564 #endif
1565 }
1566
1567
1568
1569 /**
1570  * Schedule a new task to be run with a specified delay or when any of
1571  * the specified file descriptor sets is ready.  The delay can be used
1572  * as a timeout on the socket(s) being ready.  The task will be
1573  * scheduled for execution once either the delay has expired or any of
1574  * the socket operations is ready.  This is the most general
1575  * function of the "add" family.  Note that the "prerequisite_task"
1576  * must be satisfied in addition to any of the other conditions.  In
1577  * other words, the task will be started when
1578  * <code>
1579  * (prerequisite-run)
1580  * && (delay-ready
1581  *     || any-rs-ready
1582  *     || any-ws-ready
1583  *     || (shutdown-active && run-on-shutdown) )
1584  * </code>
1585  *
1586  * @param prio how important is this task?
1587  * @param prerequisite_task run this task after the task with the given
1588  *        task identifier completes (and any of our other
1589  *        conditions, such as delay, read or write-readiness
1590  *        are satisfied).  Use GNUNET_SCHEDULER_NO_TASK to not have any dependency
1591  *        on completion of other tasks.
1592  * @param delay how long should we wait? Use GNUNET_TIME_UNIT_FOREVER_REL for "forever",
1593  *        which means that the task will only be run after we receive SIGTERM
1594  * @param rs set of file descriptors we want to read (can be NULL)
1595  * @param ws set of file descriptors we want to write (can be NULL)
1596  * @param task main function of the task
1597  * @param task_cls closure of task
1598  * @return unique task identifier for the job
1599  *         only valid until "task" is started!
1600  */
1601 GNUNET_SCHEDULER_TaskIdentifier
1602 GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio,
1603                              GNUNET_SCHEDULER_TaskIdentifier prerequisite_task,
1604                              struct GNUNET_TIME_Relative delay,
1605                              const struct GNUNET_NETWORK_FDSet *rs,
1606                              const struct GNUNET_NETWORK_FDSet *ws,
1607                              GNUNET_SCHEDULER_Task task, void *task_cls)
1608 {
1609   struct Task *t;
1610
1611 #if EXECINFO
1612   void *backtrace_array[MAX_TRACE_DEPTH];
1613 #endif
1614
1615   GNUNET_assert (active_task != NULL);
1616   GNUNET_assert (NULL != task);
1617   t = GNUNET_malloc (sizeof (struct Task));
1618   t->callback = task;
1619   t->callback_cls = task_cls;
1620 #if EXECINFO
1621   t->num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH);
1622   t->backtrace_strings =
1623       backtrace_symbols (backtrace_array, t->num_backtrace_strings);
1624 #endif
1625   t->read_fd = -1;
1626   t->write_fd = -1;
1627   if (rs != NULL)
1628   {
1629     t->read_set = GNUNET_NETWORK_fdset_create ();
1630     GNUNET_NETWORK_fdset_copy (t->read_set, rs);
1631   }
1632   if (ws != NULL)
1633   {
1634     t->write_set = GNUNET_NETWORK_fdset_create ();
1635     GNUNET_NETWORK_fdset_copy (t->write_set, ws);
1636   }
1637   t->id = ++last_id;
1638 #if PROFILE_DELAYS
1639   t->start_time = GNUNET_TIME_absolute_get ();
1640 #endif
1641   t->prereq_id = prerequisite_task;
1642   t->timeout = GNUNET_TIME_relative_to_absolute (delay);
1643   t->priority =
1644       check_priority ((prio ==
1645                        GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority :
1646                       prio);
1647   t->lifeness = current_lifeness;
1648   t->next = pending;
1649   pending = t;
1650   max_priority_added = GNUNET_MAX (max_priority_added, t->priority);
1651 #if DEBUG_TASKS
1652   LOG (GNUNET_ERROR_TYPE_DEBUG, "Adding task: %llu / %p\n", t->id,
1653        t->callback_cls);
1654 #endif
1655 #if EXECINFO
1656   int i;
1657
1658   for (i = 0; i < t->num_backtrace_strings; i++)
1659     LOG (GNUNET_ERROR_TYPE_DEBUG, "Task %llu trace %d: %s\n", t->id, i,
1660          t->backtrace_strings[i]);
1661 #endif
1662   return t->id;
1663 }
1664
1665 /* end of scheduler.c */