c09ec366ac388a9ee43b4500ed94a8c6022663d5
[oweals/gnunet.git] / src / testbed / testbed_api_operations.c
1 /*
2       This file is part of GNUnet
3       (C) 2008--2013 Christian Grothoff (and other contributing authors)
4
5       GNUnet is free software; you can redistribute it and/or modify
6       it under the terms of the GNU General Public License as published
7       by the Free Software Foundation; either version 3, or (at your
8       option) any later version.
9
10       GNUnet is distributed in the hope that it will be useful, but
11       WITHOUT ANY WARRANTY; without even the implied warranty of
12       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13       General Public License for more details.
14
15       You should have received a copy of the GNU General Public License
16       along with GNUnet; see the file COPYING.  If not, write to the
17       Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18       Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * @file testbed/testbed_api_operations.c
23  * @brief functions to manage operation queues
24  * @author Christian Grothoff
25  * @author Sree Harsha Totakura
26  */
27
28 #include "platform.h"
29 #include "testbed_api_operations.h"
30 #include "testbed_api_sd.h"
31
32
33 /**
34  * An entry in the operation queue
35  */
36 struct QueueEntry
37 {
38   /**
39    * The next DLL pointer
40    */
41   struct QueueEntry *next;
42
43   /**
44    * The prev DLL pointer
45    */
46   struct QueueEntry *prev;
47
48   /**
49    * The operation this entry holds
50    */
51   struct GNUNET_TESTBED_Operation *op;
52
53   /**
54    * How many units of resources does the operation need
55    */
56   unsigned int nres;
57 };
58
59
60 /**
61  * Queue of operations where we can only support a certain
62  * number of concurrent operations of a particular type.
63  */
64 struct OperationQueue;
65
66
67 /**
68  * A slot to record time taken by an operation
69  */
70 struct TimeSlot
71 {
72   /**
73    * DLL next pointer
74    */
75   struct TimeSlot *next;
76
77   /**
78    * DLL prev pointer
79    */
80   struct TimeSlot *prev;
81
82   /**
83    * This operation queue to which this time slot belongs to
84    */
85   struct OperationQueue *queue;
86
87   /**
88    * The operation to which this timeslot is currently allocated to
89    */
90   struct GNUNET_TESTBED_Operation *op;
91
92   /**
93    * Accumulated time
94    */
95   struct GNUNET_TIME_Relative tsum;
96
97   /**
98    * Number of timing values accumulated
99    */
100   unsigned int nvals;
101 };
102
103
104 /**
105  * Context for operation queues of type OPERATION_QUEUE_TYPE_ADAPTIVE
106  */
107 struct FeedbackCtx
108 {
109   /**
110    * Handle for calculating standard deviation
111    */
112   struct SDHandle *sd;
113
114   /**
115    * Head for DLL of time slots which are free to be allocated to operations
116    */
117   struct TimeSlot *alloc_head;
118     
119   /**
120    * Tail for DLL of time slots which are free to be allocated to operations
121    */
122   struct TimeSlot *alloc_tail;
123
124   /**
125    * Pointer to the chunk of time slots.  Free all time slots at a time using
126    * this pointer.
127    */
128   struct TimeSlot *tslots_freeptr;
129
130   /**
131    * Number of time slots filled so far
132    */
133   unsigned int tslots_filled;
134   
135   /**
136    * Bound on the maximum number of operations which can be active
137    */
138   unsigned int max_active_bound;
139
140 };
141
142
143 /**
144  * Queue of operations where we can only support a certain
145  * number of concurrent operations of a particular type.
146  */
147 struct OperationQueue
148 {
149   /**
150    * DLL head for the wait queue.  Operations which are waiting for this
151    * operation queue are put here
152    */
153   struct QueueEntry *wq_head;
154
155   /**
156    * DLL tail for the wait queue.
157    */
158   struct QueueEntry *wq_tail;
159
160   /**
161    * DLL head for the ready queue.  Operations which are in this operation queue
162    * and are in ready state are put here
163    */
164   struct QueueEntry *rq_head;
165
166   /**
167    * DLL tail for the ready queue
168    */
169   struct QueueEntry *rq_tail;
170
171   /**
172    * DLL head for the active queue.  Operations which are in this operation
173    * queue and are currently active are put here
174    */
175   struct QueueEntry *aq_head;
176
177   /**
178    * DLL tail for the active queue.
179    */
180   struct QueueEntry *aq_tail;
181
182   /**
183    * DLL head for the inactive queue.  Operations which are inactive and can be
184    * evicted if the queues it holds are maxed out and another operation begins
185    * to wait on them.
186    */
187   struct QueueEntry *nq_head;
188
189   /**
190    * DLL tail for the inactive queue.
191    */
192   struct QueueEntry *nq_tail;
193
194   /**
195    * Feedback context; only relevant for adaptive operation queues.  NULL for
196    * fixed operation queues
197    */
198   struct FeedbackCtx *fctx;
199
200   /**
201    * The type of this opeartion queue
202    */
203   enum OperationQueueType type;
204
205   /**
206    * Number of operations that are currently active in this queue.
207    */
208   unsigned int active;
209
210   /**
211    * Max number of operations which can be active at any time in this queue.
212    * This value can be changed either by calling
213    * GNUNET_TESTBED_operation_queue_reset_max_active_() or by the adaptive
214    * algorithm if this operation queue is of type OPERATION_QUEUE_TYPE_ADAPTIVE
215    */
216   unsigned int max_active;
217
218 };
219
220
221 /**
222  * Operation state
223  */
224 enum OperationState
225 {
226   /**
227    * The operation is just created and is in initial state
228    */
229   OP_STATE_INIT,
230
231   /**
232    * The operation is currently waiting for resources
233    */
234   OP_STATE_WAITING,
235
236   /**
237    * The operation is ready to be started
238    */
239   OP_STATE_READY,
240
241   /**
242    * The operation has started and is active
243    */
244   OP_STATE_ACTIVE,
245
246   /**
247    * The operation is inactive.  It still holds resources on the operation
248    * queues.  However, this operation will be evicted when another operation
249    * requires resources from the maxed out queues this operation is holding
250    * resources from.
251    */
252   OP_STATE_INACTIVE
253 };
254
255
256 /**
257  * An entry in the ready queue (implemented as DLL)
258  */
259 struct ReadyQueueEntry
260 {
261   /**
262    * next ptr for DLL
263    */
264   struct ReadyQueueEntry *next;
265   
266   /**
267    * prev ptr for DLL
268    */
269   struct ReadyQueueEntry *prev;
270
271   /**
272    * The operation associated with this entry
273    */
274   struct GNUNET_TESTBED_Operation *op;
275 };
276
277
278 /**
279  * Opaque handle to an abstract operation to be executed by the testing framework.
280  */
281 struct GNUNET_TESTBED_Operation
282 {
283   /**
284    * Function to call when we have the resources to begin the operation.
285    */
286   OperationStart start;
287
288   /**
289    * Function to call to clean up after the operation (which may or may
290    * not have been started yet).
291    */
292   OperationRelease release;
293
294   /**
295    * Closure for callbacks.
296    */
297   void *cb_cls;
298
299   /**
300    * Array of operation queues this Operation belongs to.
301    */
302   struct OperationQueue **queues;
303
304   /**
305    * Array of operation queue entries corresponding to this operation in
306    * operation queues for this operation
307    */
308   struct QueueEntry **qentries;
309
310   /**
311    * Array of number of resources an operation need from each queue. The numbers
312    * in this array should correspond to the queues array
313    */
314   unsigned int *nres;
315
316   /**
317    * Entry corresponding to this operation in ready queue.  Will be NULL if the
318    * operation is not marked as READY
319    */
320   struct ReadyQueueEntry *rq_entry;
321
322   /**
323    * Head pointer for DLL of tslots allocated to this operation
324    */
325   struct TimeSlot *tslots_head;
326
327   /**
328    * Tail pointer for DLL of tslots allocated to this operation
329    */
330   struct TimeSlot *tslots_tail;
331
332   /**
333    * The time at which the operation is started
334    */
335   struct GNUNET_TIME_Absolute tstart;
336
337   /**
338    * Number of queues in the operation queues array
339    */
340   unsigned int nqueues;
341
342   /**
343    * The state of the operation
344    */
345   enum OperationState state;
346
347   /**
348    * Is this a failed operation?
349    */
350   int failed;
351
352 };
353
354 /**
355  * DLL head for the ready queue
356  */
357 struct ReadyQueueEntry *rq_head;
358
359 /**
360  * DLL tail for the ready queue
361  */
362 struct ReadyQueueEntry *rq_tail;
363
364 /**
365  * The id of the task to process the ready queue
366  */
367 GNUNET_SCHEDULER_TaskIdentifier process_rq_task_id;
368
369
370 /**
371  * Assigns the given operation a time slot from the given operation queue
372  *
373  * @param op the operation
374  * @param queue the operation queue
375  * @return the timeslot
376  */
377 static void
378 assign_timeslot (struct GNUNET_TESTBED_Operation *op,
379                  struct OperationQueue *queue)
380 {
381   struct FeedbackCtx *fctx = queue->fctx;
382   struct TimeSlot *tslot;
383
384   GNUNET_assert (OPERATION_QUEUE_TYPE_ADAPTIVE == queue->type);
385   tslot = fctx->alloc_head;
386   GNUNET_assert (NULL != tslot);
387   GNUNET_CONTAINER_DLL_remove (fctx->alloc_head, fctx->alloc_tail, tslot);
388   GNUNET_CONTAINER_DLL_insert_tail (op->tslots_head, op->tslots_tail, tslot);
389   tslot->op = op;
390 }
391
392
393 /**
394  * Removes a queue entry of an operation from one of the operation queues' lists
395  * depending on the state of the operation
396  *
397  * @param op the operation whose entry has to be removed
398  * @param index the index of the entry in the operation's array of queue entries
399  */
400 static void
401 remove_queue_entry (struct GNUNET_TESTBED_Operation *op, unsigned int index)
402 {
403   struct OperationQueue *opq;
404   struct QueueEntry *entry;
405   
406   opq = op->queues[index];
407   entry = op->qentries[index];
408   switch (op->state)
409   {
410   case OP_STATE_INIT:
411     GNUNET_assert (0);
412     break;
413   case OP_STATE_WAITING:
414     GNUNET_CONTAINER_DLL_remove (opq->wq_head, opq->wq_tail, entry);
415     break;
416   case OP_STATE_READY:
417     GNUNET_CONTAINER_DLL_remove (opq->rq_head, opq->rq_tail, entry);
418     break;
419   case OP_STATE_ACTIVE:
420     GNUNET_CONTAINER_DLL_remove (opq->aq_head, opq->aq_tail, entry);
421     break;
422   case OP_STATE_INACTIVE:
423     GNUNET_CONTAINER_DLL_remove (opq->nq_head, opq->nq_tail, entry);
424     break;
425   }
426 }
427
428
429 /**
430  * Changes the state of the operation while moving its associated queue entries
431  * in the operation's operation queues
432  *
433  * @param op the operation whose state has to be changed
434  * @param state the state the operation should have.  It cannot be OP_STATE_INIT
435  */
436 static void
437 change_state (struct GNUNET_TESTBED_Operation *op, enum OperationState state)
438 {
439   struct QueueEntry *entry;
440   struct OperationQueue *opq;
441   unsigned int cnt;
442   unsigned int s;
443   
444   GNUNET_assert (OP_STATE_INIT != state);
445   GNUNET_assert (NULL != op->queues);
446   GNUNET_assert (NULL != op->nres);
447   GNUNET_assert ((OP_STATE_INIT == op->state) || (NULL != op->qentries));
448   GNUNET_assert (op->state != state);
449   for (cnt = 0; cnt < op->nqueues; cnt++)
450   {
451     if (OP_STATE_INIT == op->state)
452     {
453       entry = GNUNET_malloc (sizeof (struct QueueEntry));
454       entry->op = op;
455       entry->nres = op->nres[cnt];
456       s = cnt;
457       GNUNET_array_append (op->qentries, s, entry);      
458     }
459     else
460     {
461       entry = op->qentries[cnt];
462       remove_queue_entry (op, cnt);
463     }
464     opq = op->queues[cnt];
465     switch (state)
466     {
467     case OP_STATE_INIT:
468       GNUNET_assert (0);
469       break;
470     case OP_STATE_WAITING:
471       GNUNET_CONTAINER_DLL_insert_tail (opq->wq_head, opq->wq_tail, entry);
472       break;
473     case OP_STATE_READY:
474       GNUNET_CONTAINER_DLL_insert_tail (opq->rq_head, opq->rq_tail, entry);
475       break;
476     case OP_STATE_ACTIVE:
477       GNUNET_CONTAINER_DLL_insert_tail (opq->aq_head, opq->aq_tail, entry);
478       break;
479     case OP_STATE_INACTIVE:
480       GNUNET_CONTAINER_DLL_insert_tail (opq->nq_head, opq->nq_tail, entry);
481       break;
482     }
483   }
484   op->state = state;
485 }
486
487
488 /**
489  * Removes an operation from the ready queue.  Also stops the 'process_rq_task'
490  * if the given operation is the last one in the queue.
491  *
492  * @param op the operation to be removed
493  */
494 static void
495 rq_remove (struct GNUNET_TESTBED_Operation *op)
496 {  
497   GNUNET_assert (NULL != op->rq_entry);
498   GNUNET_CONTAINER_DLL_remove (rq_head, rq_tail, op->rq_entry);
499   GNUNET_free (op->rq_entry);
500   op->rq_entry = NULL;
501   if ( (NULL == rq_head) && (GNUNET_SCHEDULER_NO_TASK != process_rq_task_id) )
502   {
503     GNUNET_SCHEDULER_cancel (process_rq_task_id);
504     process_rq_task_id = GNUNET_SCHEDULER_NO_TASK;
505   }
506 }
507
508
509 /**
510  * Processes the ready queue by calling the operation start callback of the
511  * operation at the head.  The operation is then removed from the queue.  The
512  * task is scheduled to run again immediately until no more operations are in
513  * the ready queue.
514  *
515  * @param cls NULL
516  * @param tc scheduler task context.  Not used.
517  */
518 static void
519 process_rq_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
520 {
521   struct GNUNET_TESTBED_Operation *op;
522   struct OperationQueue *queue;
523   unsigned int cnt;
524
525   process_rq_task_id = GNUNET_SCHEDULER_NO_TASK;
526   GNUNET_assert (NULL != rq_head);
527   GNUNET_assert (NULL != (op = rq_head->op));
528   rq_remove (op);
529   if (NULL != rq_head)
530     process_rq_task_id = GNUNET_SCHEDULER_add_now (&process_rq_task, NULL);
531   change_state (op, OP_STATE_ACTIVE);
532   for (cnt = 0; cnt < op->nqueues; cnt++)
533   {
534     queue = op->queues[cnt];
535     if (OPERATION_QUEUE_TYPE_ADAPTIVE == queue->type)
536       assign_timeslot (op, queue);
537   }
538   op->tstart = GNUNET_TIME_absolute_get ();
539   if (NULL != op->start)
540     op->start (op->cb_cls);
541 }
542
543
544 /**
545  * Adds the operation to the ready queue and starts the 'process_rq_task'
546  *
547  * @param op the operation to be queued
548  */
549 static void
550 rq_add (struct GNUNET_TESTBED_Operation *op)
551 {
552   struct ReadyQueueEntry *rq_entry;
553
554   GNUNET_assert (NULL == op->rq_entry);
555   rq_entry = GNUNET_malloc (sizeof (struct ReadyQueueEntry));
556   rq_entry->op = op;
557   GNUNET_CONTAINER_DLL_insert_tail (rq_head, rq_tail, rq_entry);
558   op->rq_entry = rq_entry;
559   if (GNUNET_SCHEDULER_NO_TASK == process_rq_task_id)
560     process_rq_task_id = GNUNET_SCHEDULER_add_now (&process_rq_task, NULL);
561 }
562
563
564 /**
565  * Checks if the given operation queue is empty or not
566  *
567  * @param opq the operation queue
568  * @return GNUNET_YES if the given operation queue has no operations; GNUNET_NO
569  *           otherwise
570  */
571 static int
572 is_queue_empty (struct OperationQueue *opq)
573 {
574   if ( (NULL != opq->wq_head)
575        || (NULL != opq->rq_head)
576        || (NULL != opq->aq_head)
577        || (NULL != opq->nq_head) )
578     return GNUNET_NO;
579   return GNUNET_YES;
580 }
581
582
583 /**
584  * Checks if the given operation queue has enough resources to provide for the
585  * operation of the given queue entry.  It also checks if any inactive
586  * operations are to be released in order to accommodate the needed resources
587  * and returns them as an array.
588  *
589  * @param opq the operation queue to check for resource accommodation
590  * @param entry the operation queue entry whose operation's resources are to be
591  *          accommodated
592  * @param ops_ pointer to return the array of operations which are to be released
593  *          in order to accommodate the new operation.  Can be NULL
594  * @param n_ops_ the number of operations in ops_
595  * @return GNUNET_YES if the given entry's operation can be accommodated in this
596  *           queue. GNUNET_NO if it cannot be accommodated; ops_ and n_ops_ will
597  *           be set to NULL and 0 respectively.
598  */
599 static int
600 decide_capacity (struct OperationQueue *opq,
601                  struct QueueEntry *entry,
602                  struct GNUNET_TESTBED_Operation ***ops_,
603                  unsigned int *n_ops_)
604 {
605   struct QueueEntry **evict_entries;
606   struct GNUNET_TESTBED_Operation **ops;
607   struct GNUNET_TESTBED_Operation *op;
608   unsigned int n_ops;
609   unsigned int n_evict_entries;
610   unsigned int need;
611   int deficit;
612   int rval;
613
614   GNUNET_assert (NULL != (op = entry->op));
615   GNUNET_assert (0 < (need = entry->nres));
616   ops = NULL;
617   n_ops = 0;
618   evict_entries = NULL;
619   n_evict_entries = 0;
620   rval = GNUNET_YES;
621   if (opq->active > opq->max_active)
622   {
623     rval = GNUNET_NO;
624     goto ret;
625   }
626   if ((opq->active + need) <= opq->max_active)
627     goto ret;
628   deficit = need - (opq->max_active - opq->active);
629   for (entry = opq->nq_head;
630        (0 < deficit) && (NULL != entry);
631        entry = entry->next)
632   {
633     GNUNET_array_append (evict_entries, n_evict_entries, entry);
634     deficit -= entry->nres;
635   }
636   if (0 < deficit)
637   {
638     rval = GNUNET_NO;
639     goto ret;
640   }
641   for (n_ops = 0; n_ops < n_evict_entries;)
642   {
643     op = evict_entries[n_ops]->op;
644     GNUNET_array_append (ops, n_ops, op); /* increments n-ops */
645   }
646
647  ret:
648   GNUNET_free_non_null (evict_entries);  
649   if (NULL != ops_)
650     *ops_ = ops;
651   else
652     GNUNET_free (ops);
653   if (NULL != n_ops_)
654     *n_ops_ = n_ops;
655   return rval;
656 }
657
658
659 /**
660  * Merges an array of operations into another, eliminating duplicates.  No
661  * ordering is guaranteed.
662  *
663  * @param old the array into which the merging is done.
664  * @param n_old the number of operations in old array
665  * @param new the array from which operations are to be merged
666  * @param n_new the number of operations in new array
667  */
668 static void
669 merge_ops (struct GNUNET_TESTBED_Operation ***old,
670            unsigned int *n_old,
671            struct GNUNET_TESTBED_Operation **new,
672            unsigned int n_new)
673 {
674   struct GNUNET_TESTBED_Operation **cur;
675   unsigned int i;
676   unsigned int j;
677   unsigned int n_cur;
678  
679   GNUNET_assert (NULL != old);
680   n_cur = *n_old;
681   cur = *old;
682   for (i = 0; i < n_new; i++)
683   {    
684     for (j = 0; j < *n_old; j++)
685     {
686       if (new[i] == cur[j])
687         break;
688     }
689     if (j < *n_old)
690       continue;
691     GNUNET_array_append (cur, n_cur, new[j]);
692   }
693   *old = cur;
694   *n_old = n_cur;
695 }
696            
697
698
699 /**
700  * Checks for the readiness of an operation and schedules a operation start task
701  *
702  * @param op the operation
703  */
704 static int
705 check_readiness (struct GNUNET_TESTBED_Operation *op)
706 {
707   struct GNUNET_TESTBED_Operation **evict_ops;
708   struct GNUNET_TESTBED_Operation **ops;
709   unsigned int n_ops;
710   unsigned int n_evict_ops;
711   unsigned int i;
712
713   GNUNET_assert (NULL == op->rq_entry);
714   GNUNET_assert (OP_STATE_WAITING == op->state);
715   evict_ops = NULL;
716   n_evict_ops = 0;
717   for (i = 0; i < op->nqueues; i++)
718   {
719     ops = NULL;
720     n_ops = 0;
721     if (GNUNET_NO == decide_capacity (op->queues[i], op->qentries[i],
722                                       &ops, &n_ops))
723     {
724       GNUNET_free_non_null (evict_ops);
725       return GNUNET_NO;
726     }
727     if (NULL == ops)
728       continue;
729     merge_ops (&evict_ops, &n_evict_ops, ops, n_ops);
730     GNUNET_free (ops);    
731   }
732   if (NULL != evict_ops)
733   {
734     for (i = 0; i < n_evict_ops; i++)
735       GNUNET_TESTBED_operation_release_ (evict_ops[i]); 
736     GNUNET_free (evict_ops);
737     evict_ops = NULL;
738     /* Evicting the operations should schedule this operation */
739     GNUNET_assert (OP_STATE_READY == op->state);
740     return GNUNET_YES;
741   }
742   for (i = 0; i < op->nqueues; i++)
743     op->queues[i]->active += op->nres[i];
744   change_state (op, OP_STATE_READY);
745   rq_add (op);
746   return GNUNET_YES;
747 }
748
749
750 /**
751  * Defers a ready to be executed operation back to waiting
752  *
753  * @param op the operation to defer
754  */
755 static void
756 defer (struct GNUNET_TESTBED_Operation *op)
757 {
758   unsigned int i;
759
760   GNUNET_assert (OP_STATE_READY == op->state);
761   rq_remove (op);
762   for (i = 0; i < op->nqueues; i++)
763   {
764     GNUNET_assert (op->queues[i]->active >= op->nres[i]);
765     op->queues[i]->active -= op->nres[i];    
766   }
767   change_state (op, OP_STATE_WAITING);
768 }
769
770
771 /**
772  * Cleanups the array of timeslots of an operation queue.  For each time slot in
773  * the array, if it is allocated to an operation, it will be deallocated from
774  * the operation
775  *
776  * @param queue the operation queue
777  */
778 static void
779 cleanup_tslots (struct OperationQueue *queue)
780 {
781   struct FeedbackCtx *fctx = queue->fctx;
782   struct TimeSlot *tslot;
783   struct GNUNET_TESTBED_Operation *op;
784   unsigned int cnt;
785
786   GNUNET_assert (NULL != fctx);
787   for (cnt = 0; cnt < queue->max_active; cnt++)
788   {
789     tslot = &fctx->tslots_freeptr[cnt];
790     op = tslot->op;
791     if (NULL == op)
792       continue;
793     GNUNET_CONTAINER_DLL_remove (op->tslots_head, op->tslots_tail, tslot);
794   }
795   GNUNET_free_non_null (fctx->tslots_freeptr);
796   fctx->tslots_freeptr = NULL;
797   fctx->alloc_head = NULL;
798   fctx->alloc_tail = NULL;
799   fctx->tslots_filled = 0;
800 }
801
802
803 /**
804  * Initializes the operation queue for parallel overlay connects
805  *
806  * @param h the host handle
807  * @param npoc the number of parallel overlay connects - the queue size
808  */
809 static void
810 adaptive_queue_set_max_active (struct OperationQueue *queue, unsigned int n)
811 {
812   struct FeedbackCtx *fctx = queue->fctx;
813   struct TimeSlot *tslot;
814   unsigned int cnt;
815   
816   cleanup_tslots (queue);
817   n = GNUNET_MIN (n ,fctx->max_active_bound);
818   fctx->tslots_freeptr = GNUNET_malloc (n * sizeof (struct TimeSlot));
819   for (cnt = 0; cnt < n; cnt++)
820   {
821     tslot = &fctx->tslots_freeptr[cnt];
822     tslot->queue = queue;
823     GNUNET_CONTAINER_DLL_insert_tail (fctx->alloc_head, fctx->alloc_tail, tslot);
824   }
825   GNUNET_TESTBED_operation_queue_reset_max_active_ (queue, n);
826 }
827
828
829 /**
830  * Adapts parallelism in an adaptive queue by using the statistical data from
831  * the feedback context.
832  *
833  * @param queue the queue
834  * @param fail GNUNET_YES if the last operation failed; GNUNET_NO if not;
835  */
836 static void
837 adapt_parallelism (struct OperationQueue *queue, int fail)
838 {
839   struct GNUNET_TIME_Relative avg;
840   struct FeedbackCtx *fctx;
841   struct TimeSlot *tslot;
842   int sd;
843   unsigned int nvals;
844   unsigned int cnt;
845
846   avg = GNUNET_TIME_UNIT_ZERO;
847   nvals = 0;
848   fctx = queue->fctx;
849   for (cnt = 0; cnt < queue->max_active; cnt++)
850   {
851     tslot = &fctx->tslots_freeptr[cnt];
852     avg = GNUNET_TIME_relative_add (avg, tslot->tsum);
853     nvals += tslot->nvals;
854   }
855   GNUNET_assert (nvals >= queue->max_active);
856   avg = GNUNET_TIME_relative_divide (avg, nvals);
857   if (GNUNET_SYSERR == 
858       GNUNET_TESTBED_SD_deviation_factor_ (fctx->sd,
859                                            (unsigned int) avg.rel_value_us,
860                                            &sd))
861   {
862     GNUNET_TESTBED_SD_add_data_ (fctx->sd, (unsigned int) avg.rel_value_us);
863     adaptive_queue_set_max_active (queue, queue->max_active); /* no change */
864     return;
865   }
866   if ((0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, queue->max_active)))
867     GNUNET_TESTBED_SD_add_data_ (fctx->sd, (unsigned int) avg.rel_value_us);
868   if (sd < 0)
869     sd = 0;
870   GNUNET_assert (0 <= sd);
871   if ((0 == sd) && (! fail))
872   {
873     adaptive_queue_set_max_active (queue, queue->max_active * 2);
874     return;
875   }
876   if ((1 == sd) && (! fail))
877   {
878     adaptive_queue_set_max_active (queue, queue->max_active + 1);
879     return;
880   }
881   if (1 == queue->max_active)
882   {
883     adaptive_queue_set_max_active (queue, 1);
884     return;
885   }
886   if (((sd < 2) && (fail)) || (2 == sd))
887   {
888     adaptive_queue_set_max_active (queue, queue->max_active - 1);
889     return;
890   }
891   adaptive_queue_set_max_active (queue, queue->max_active / 2);
892 }
893
894
895 /**
896  * update tslots with the operation's completion time.  Additionally, if
897  * updating a timeslot makes all timeslots filled in an adaptive operation
898  * queue, call adapt_parallelism() for that queue.
899  *
900  * @param op the operation
901  */
902 static void
903 update_tslots (struct GNUNET_TESTBED_Operation *op)
904 {
905   struct OperationQueue *queue;
906   struct GNUNET_TIME_Relative t;
907   struct TimeSlot *tslot;
908   struct FeedbackCtx *fctx;
909   
910   t = GNUNET_TIME_absolute_get_duration (op->tstart);
911   while (NULL != (tslot = op->tslots_head)) /* update time slots */
912   {
913     queue = tslot->queue;
914     fctx = queue->fctx;
915     tslot->tsum = GNUNET_TIME_relative_add (tslot->tsum, t);
916     GNUNET_CONTAINER_DLL_remove (op->tslots_head, op->tslots_tail, tslot);
917     tslot->op = NULL;    
918     GNUNET_CONTAINER_DLL_insert_tail (fctx->alloc_head, fctx->alloc_tail,
919   tslot);
920     if (0 != tslot->nvals++)
921       continue;
922     fctx->tslots_filled++;
923     if (queue->max_active == fctx->tslots_filled)
924       adapt_parallelism (queue, op->failed);
925   }
926 }
927
928
929 /**
930  * Create an 'operation' to be performed.
931  *
932  * @param cls closure for the callbacks
933  * @param start function to call to start the operation
934  * @param release function to call to close down the operation
935  * @return handle to the operation
936  */
937 struct GNUNET_TESTBED_Operation *
938 GNUNET_TESTBED_operation_create_ (void *cls, OperationStart start,
939                                   OperationRelease release)
940 {
941   struct GNUNET_TESTBED_Operation *op;
942
943   op = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Operation));
944   op->start = start;
945   op->state = OP_STATE_INIT;
946   op->release = release;
947   op->cb_cls = cls;
948   return op;
949 }
950
951
952 /**
953  * Create an operation queue.
954  *
955  * @param type the type of operation queue
956  * @param max_active maximum number of operations in this
957  *        queue that can be active in parallel at the same time
958  * @return handle to the queue
959  */
960 struct OperationQueue *
961 GNUNET_TESTBED_operation_queue_create_ (enum OperationQueueType type,
962                                         unsigned int max_active)
963 {
964   struct OperationQueue *queue;
965   struct FeedbackCtx *fctx;
966
967   queue = GNUNET_malloc (sizeof (struct OperationQueue));
968   queue->type = type;
969   if (OPERATION_QUEUE_TYPE_FIXED == type)
970   {
971     queue->max_active = max_active;
972   }
973   else
974   {
975     fctx = GNUNET_malloc (sizeof (struct FeedbackCtx));
976     fctx->max_active_bound = max_active;
977     fctx->sd = GNUNET_TESTBED_SD_init_ (10); /* FIXME: Why 10? */
978     queue->fctx = fctx;
979     adaptive_queue_set_max_active (queue, 1); /* start with 1 */
980   }
981   return queue;
982 }
983
984
985 /**
986  * Destroy an operation queue.  The queue MUST be empty
987  * at this time.
988  *
989  * @param queue queue to destroy
990  */
991 void
992 GNUNET_TESTBED_operation_queue_destroy_ (struct OperationQueue *queue)
993 {
994   struct FeedbackCtx *fctx;
995   
996   GNUNET_break (GNUNET_YES == is_queue_empty (queue));
997   if (OPERATION_QUEUE_TYPE_ADAPTIVE == queue->type)
998   {
999     cleanup_tslots (queue);
1000     fctx = queue->fctx;
1001     GNUNET_TESTBED_SD_destroy_ (fctx->sd);
1002     GNUNET_free (fctx);
1003   }
1004   GNUNET_free (queue);
1005 }
1006
1007
1008 /**
1009  * Destroys the operation queue if it is empty.  If not empty return GNUNET_NO.
1010  *
1011  * @param queue the queue to destroy if empty
1012  * @return GNUNET_YES if the queue is destroyed.  GNUNET_NO if not (because it
1013  *           is not empty)
1014  */
1015 int
1016 GNUNET_TESTBED_operation_queue_destroy_empty_ (struct OperationQueue *queue)
1017 {
1018   if (GNUNET_NO == is_queue_empty (queue))
1019     return GNUNET_NO;
1020   GNUNET_TESTBED_operation_queue_destroy_ (queue);
1021   return GNUNET_YES;
1022 }
1023
1024
1025 /**
1026  * Rechecks if any of the operations in the given operation queue's waiting list
1027  * can be made active
1028  *
1029  * @param opq the operation queue
1030  */
1031 static void
1032 recheck_waiting (struct OperationQueue *opq)
1033 {
1034   struct QueueEntry *entry;
1035   struct QueueEntry *entry2;
1036
1037   entry = opq->wq_head;
1038   while (NULL != entry)
1039   {
1040     entry2 = entry->next;
1041     if (GNUNET_NO == check_readiness (entry->op))
1042       break;
1043     entry = entry2;
1044   }
1045 }
1046
1047
1048 /**
1049  * Function to reset the maximum number of operations in the given queue. If
1050  * max_active is lesser than the number of currently active operations, the
1051  * active operations are not stopped immediately.
1052  *
1053  * @param queue the operation queue which has to be modified
1054  * @param max_active the new maximum number of active operations
1055  */
1056 void
1057 GNUNET_TESTBED_operation_queue_reset_max_active_ (struct OperationQueue *queue,
1058                                                   unsigned int max_active)
1059 {
1060   struct QueueEntry *entry;
1061
1062   queue->max_active = max_active;
1063   while ( (queue->active > queue->max_active)
1064           && (NULL != (entry = queue->rq_head)) )
1065     defer (entry->op);
1066   recheck_waiting (queue);
1067 }
1068
1069
1070 /**
1071  * Add an operation to a queue.  An operation can be in multiple queues at
1072  * once. Once the operation is inserted into all the queues
1073  * GNUNET_TESTBED_operation_begin_wait_() has to be called to actually start
1074  * waiting for the operation to become active.
1075  *
1076  * @param queue queue to add the operation to
1077  * @param op operation to add to the queue
1078  * @param nres the number of units of the resources of queue needed by the
1079  *          operation. Should be greater than 0.
1080  */
1081 void
1082 GNUNET_TESTBED_operation_queue_insert2_ (struct OperationQueue *queue,
1083                                          struct GNUNET_TESTBED_Operation *op,
1084                                          unsigned int nres)
1085 {
1086   unsigned int qsize;
1087
1088   GNUNET_assert (0 < nres);
1089   qsize = op->nqueues;
1090   GNUNET_array_append (op->queues, op->nqueues, queue);
1091   GNUNET_array_append (op->nres, qsize, nres);
1092   GNUNET_assert (qsize == op->nqueues);
1093 }
1094
1095
1096 /**
1097  * Add an operation to a queue.  An operation can be in multiple queues at
1098  * once. Once the operation is inserted into all the queues
1099  * GNUNET_TESTBED_operation_begin_wait_() has to be called to actually start
1100  * waiting for the operation to become active. The operation is assumed to take
1101  * 1 queue resource. Use GNUNET_TESTBED_operation_queue_insert2_() if it
1102  * requires more than 1
1103  *
1104  * @param queue queue to add the operation to
1105  * @param op operation to add to the queue
1106  */
1107 void
1108 GNUNET_TESTBED_operation_queue_insert_ (struct OperationQueue *queue,
1109                                         struct GNUNET_TESTBED_Operation *op)
1110 {
1111   return GNUNET_TESTBED_operation_queue_insert2_ (queue, op, 1);
1112 }
1113
1114
1115 /**
1116  * Marks the given operation as waiting on the queues.  Once all queues permit
1117  * the operation to become active, the operation will be activated.  The actual
1118  * activation will occur in a separate task (thus allowing multiple queue
1119  * insertions to be made without having the first one instantly trigger the
1120  * operation if the first queue has sufficient resources).
1121  *
1122  * @param op the operation to marks as waiting
1123  */
1124 void
1125 GNUNET_TESTBED_operation_begin_wait_ (struct GNUNET_TESTBED_Operation *op)
1126 {
1127   GNUNET_assert (NULL == op->rq_entry);
1128   change_state (op, OP_STATE_WAITING);
1129   (void) check_readiness (op);
1130 }
1131
1132
1133 /**
1134  * Marks an active operation as inactive - the operation will be kept in a
1135  * ready-to-be-released state and continues to hold resources until another
1136  * operation contents for them.
1137  *
1138  * @param op the operation to be marked as inactive.  The operation start
1139  *          callback should have been called before for this operation to mark
1140  *          it as inactive.
1141  */
1142 void
1143 GNUNET_TESTBED_operation_inactivate_ (struct GNUNET_TESTBED_Operation *op)
1144 {
1145   struct OperationQueue **queues;
1146   size_t ms;
1147   unsigned int nqueues;
1148   unsigned int i;
1149
1150   GNUNET_assert (OP_STATE_ACTIVE == op->state);
1151   change_state (op, OP_STATE_INACTIVE);
1152   nqueues = op->nqueues;
1153   ms = sizeof (struct OperationQueue *) * nqueues;
1154   queues = GNUNET_malloc (ms);
1155   /* Cloning is needed as the operation be released by waiting operations and
1156      hence its nqueues memory ptr will be freed */
1157   GNUNET_assert (NULL != (queues = memcpy (queues, op->queues, ms)));
1158   for (i = 0; i < nqueues; i++)
1159     recheck_waiting (queues[i]);
1160   GNUNET_free (queues);
1161 }
1162
1163
1164 /**
1165  * Marks and inactive operation as active.  This fuction should be called to
1166  * ensure that the oprelease callback will not be called until it is either
1167  * marked as inactive or released.
1168  *
1169  * @param op the operation to be marked as active
1170  */
1171 void
1172 GNUNET_TESTBED_operation_activate_ (struct GNUNET_TESTBED_Operation *op)
1173 {
1174
1175   GNUNET_assert (OP_STATE_INACTIVE == op->state);
1176   change_state (op, OP_STATE_ACTIVE);
1177 }
1178
1179
1180 /**
1181  * An operation is 'done' (was cancelled or finished); remove
1182  * it from the queues and release associated resources.
1183  *
1184  * @param op operation that finished
1185  */
1186 void
1187 GNUNET_TESTBED_operation_release_ (struct GNUNET_TESTBED_Operation *op)
1188 {
1189   struct QueueEntry *entry;  
1190   struct OperationQueue *opq;
1191   unsigned int i;
1192
1193   if (OP_STATE_INIT == op->state)
1194   {
1195     GNUNET_free (op);
1196     return;
1197   }
1198   if (OP_STATE_READY == op->state)
1199     rq_remove (op);
1200   if (OP_STATE_INACTIVE == op->state) /* Activate the operation if inactive */
1201     GNUNET_TESTBED_operation_activate_ (op);
1202   if (OP_STATE_ACTIVE == op->state)
1203     update_tslots (op);
1204   GNUNET_assert (NULL != op->queues);
1205   GNUNET_assert (NULL != op->qentries);  
1206   for (i = 0; i < op->nqueues; i++)
1207   {
1208     entry = op->qentries[i];
1209     remove_queue_entry (op, i);
1210     opq = op->queues[i];
1211     switch (op->state)
1212     {      
1213     case OP_STATE_INIT:
1214     case OP_STATE_INACTIVE:
1215       GNUNET_assert (0);
1216       break;
1217     case OP_STATE_WAITING:      
1218       break;
1219     case OP_STATE_ACTIVE:
1220     case OP_STATE_READY:
1221       GNUNET_assert (0 != opq->active);
1222       GNUNET_assert (opq->active >= entry->nres);
1223       opq->active -= entry->nres;
1224       recheck_waiting (opq);
1225       break;
1226     }    
1227     GNUNET_free (entry);
1228   }
1229   GNUNET_free_non_null (op->qentries);
1230   GNUNET_free (op->queues);
1231   GNUNET_free (op->nres);
1232   if (NULL != op->release)
1233     op->release (op->cb_cls);
1234   GNUNET_free (op);
1235 }
1236
1237
1238 /**
1239  * Marks an operation as failed
1240  *
1241  * @param op the operation to be marked as failed
1242  */
1243 void
1244 GNUNET_TESTBED_operation_mark_failed (struct GNUNET_TESTBED_Operation *op)
1245 {
1246   op->failed = GNUNET_YES;
1247 }
1248
1249
1250 /* end of testbed_api_operations.c */