fix 2893: Move adaptive parallelisation mechanism to operation queues
[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   sd = GNUNET_TESTBED_SD_deviation_factor_ (fctx->sd, (unsigned int)
858                                             avg.rel_value_us);
859   if ( (sd <= 5) ||
860        (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
861                                        queue->max_active)) )
862     GNUNET_TESTBED_SD_add_data_ (fctx->sd, (unsigned int) avg.rel_value_us);
863   if (GNUNET_SYSERR == sd)
864   {
865     adaptive_queue_set_max_active (queue, queue->max_active); /* no change */
866     return;
867   }
868   GNUNET_assert (0 <= sd);
869   if ((0 == sd) && (! fail))
870   {
871     adaptive_queue_set_max_active (queue, queue->max_active * 2);
872     return;
873   }
874   if ((1 == sd) && (! fail))
875   {
876     adaptive_queue_set_max_active (queue, queue->max_active + 1);
877     return;
878   }
879   if (1 == queue->max_active)
880   {
881     adaptive_queue_set_max_active (queue, 1);
882     return;
883   }
884   if (((sd < 2) && (fail)) || (2 == sd))
885   {
886     adaptive_queue_set_max_active (queue, queue->max_active - 1);
887     return;
888   }
889   adaptive_queue_set_max_active (queue, queue->max_active / 2);
890 }
891
892
893 /**
894  * update tslots with the operation's completion time.  Additionally, if
895  * updating a timeslot makes all timeslots filled in an adaptive operation
896  * queue, call adapt_parallelism() for that queue.
897  *
898  * @param op the operation
899  */
900 static void
901 update_tslots (struct GNUNET_TESTBED_Operation *op)
902 {
903   struct OperationQueue *queue;
904   struct GNUNET_TIME_Relative t;
905   struct TimeSlot *tslot;
906   struct FeedbackCtx *fctx;
907   
908   t = GNUNET_TIME_absolute_get_duration (op->tstart);
909   while (NULL != (tslot = op->tslots_head)) /* update time slots */
910   {
911     queue = tslot->queue;
912     fctx = queue->fctx;
913     tslot->tsum = GNUNET_TIME_relative_add (tslot->tsum, t);
914     GNUNET_CONTAINER_DLL_remove (op->tslots_head, op->tslots_tail, tslot);
915     tslot->op = NULL;    
916     GNUNET_CONTAINER_DLL_insert_tail (fctx->alloc_head, fctx->alloc_tail,
917   tslot);
918     if (0 != tslot->nvals++)
919       continue;
920     fctx->tslots_filled++;
921     if (queue->max_active == fctx->tslots_filled)
922       adapt_parallelism (queue, op->failed);
923   }
924 }
925
926
927 /**
928  * Create an 'operation' to be performed.
929  *
930  * @param cls closure for the callbacks
931  * @param start function to call to start the operation
932  * @param release function to call to close down the operation
933  * @return handle to the operation
934  */
935 struct GNUNET_TESTBED_Operation *
936 GNUNET_TESTBED_operation_create_ (void *cls, OperationStart start,
937                                   OperationRelease release)
938 {
939   struct GNUNET_TESTBED_Operation *op;
940
941   op = GNUNET_malloc (sizeof (struct GNUNET_TESTBED_Operation));
942   op->start = start;
943   op->state = OP_STATE_INIT;
944   op->release = release;
945   op->cb_cls = cls;
946   return op;
947 }
948
949
950 /**
951  * Create an operation queue.
952  *
953  * @param type the type of operation queue
954  * @param max_active maximum number of operations in this
955  *        queue that can be active in parallel at the same time
956  * @return handle to the queue
957  */
958 struct OperationQueue *
959 GNUNET_TESTBED_operation_queue_create_ (enum OperationQueueType type,
960                                         unsigned int max_active)
961 {
962   struct OperationQueue *queue;
963   struct FeedbackCtx *fctx;
964
965   queue = GNUNET_malloc (sizeof (struct OperationQueue));
966   queue->type = type;
967   if (OPERATION_QUEUE_TYPE_FIXED == type)
968   {
969     queue->max_active = max_active;
970   }
971   else
972   {
973     fctx = GNUNET_malloc (sizeof (struct FeedbackCtx));
974     fctx->max_active_bound = max_active;
975     fctx->sd = GNUNET_TESTBED_SD_init_ (10); /* FIXME: Why 10? */
976     queue->fctx = fctx;
977     adaptive_queue_set_max_active (queue, 1); /* start with 1 */
978   }
979   return queue;
980 }
981
982
983 /**
984  * Destroy an operation queue.  The queue MUST be empty
985  * at this time.
986  *
987  * @param queue queue to destroy
988  */
989 void
990 GNUNET_TESTBED_operation_queue_destroy_ (struct OperationQueue *queue)
991 {
992   struct FeedbackCtx *fctx;
993   
994   GNUNET_break (GNUNET_YES == is_queue_empty (queue));
995   if (OPERATION_QUEUE_TYPE_ADAPTIVE == queue->type)
996   {
997     cleanup_tslots (queue);
998     fctx = queue->fctx;
999     GNUNET_TESTBED_SD_destroy_ (fctx->sd);
1000     GNUNET_free (fctx);
1001   }
1002   GNUNET_free (queue);
1003 }
1004
1005
1006 /**
1007  * Destroys the operation queue if it is empty.  If not empty return GNUNET_NO.
1008  *
1009  * @param queue the queue to destroy if empty
1010  * @return GNUNET_YES if the queue is destroyed.  GNUNET_NO if not (because it
1011  *           is not empty)
1012  */
1013 int
1014 GNUNET_TESTBED_operation_queue_destroy_empty_ (struct OperationQueue *queue)
1015 {
1016   if (GNUNET_NO == is_queue_empty (queue))
1017     return GNUNET_NO;
1018   GNUNET_TESTBED_operation_queue_destroy_ (queue);
1019   return GNUNET_YES;
1020 }
1021
1022
1023 /**
1024  * Rechecks if any of the operations in the given operation queue's waiting list
1025  * can be made active
1026  *
1027  * @param opq the operation queue
1028  */
1029 static void
1030 recheck_waiting (struct OperationQueue *opq)
1031 {
1032   struct QueueEntry *entry;
1033   struct QueueEntry *entry2;
1034
1035   entry = opq->wq_head;
1036   while (NULL != entry)
1037   {
1038     entry2 = entry->next;
1039     if (GNUNET_NO == check_readiness (entry->op))
1040       break;
1041     entry = entry2;
1042   }
1043 }
1044
1045
1046 /**
1047  * Function to reset the maximum number of operations in the given queue. If
1048  * max_active is lesser than the number of currently active operations, the
1049  * active operations are not stopped immediately.
1050  *
1051  * @param queue the operation queue which has to be modified
1052  * @param max_active the new maximum number of active operations
1053  */
1054 void
1055 GNUNET_TESTBED_operation_queue_reset_max_active_ (struct OperationQueue *queue,
1056                                                   unsigned int max_active)
1057 {
1058   struct QueueEntry *entry;
1059
1060   queue->max_active = max_active;
1061   while ( (queue->active > queue->max_active)
1062           && (NULL != (entry = queue->rq_head)) )
1063     defer (entry->op);
1064   recheck_waiting (queue);
1065 }
1066
1067
1068 /**
1069  * Add an operation to a queue.  An operation can be in multiple queues at
1070  * once. Once the operation is inserted into all the queues
1071  * GNUNET_TESTBED_operation_begin_wait_() has to be called to actually start
1072  * waiting for the operation to become active.
1073  *
1074  * @param queue queue to add the operation to
1075  * @param op operation to add to the queue
1076  * @param nres the number of units of the resources of queue needed by the
1077  *          operation. Should be greater than 0.
1078  */
1079 void
1080 GNUNET_TESTBED_operation_queue_insert2_ (struct OperationQueue *queue,
1081                                          struct GNUNET_TESTBED_Operation *op,
1082                                          unsigned int nres)
1083 {
1084   unsigned int qsize;
1085
1086   GNUNET_assert (0 < nres);
1087   qsize = op->nqueues;
1088   GNUNET_array_append (op->queues, op->nqueues, queue);
1089   GNUNET_array_append (op->nres, qsize, nres);
1090   GNUNET_assert (qsize == op->nqueues);
1091 }
1092
1093
1094 /**
1095  * Add an operation to a queue.  An operation can be in multiple queues at
1096  * once. Once the operation is inserted into all the queues
1097  * GNUNET_TESTBED_operation_begin_wait_() has to be called to actually start
1098  * waiting for the operation to become active. The operation is assumed to take
1099  * 1 queue resource. Use GNUNET_TESTBED_operation_queue_insert2_() if it
1100  * requires more than 1
1101  *
1102  * @param queue queue to add the operation to
1103  * @param op operation to add to the queue
1104  */
1105 void
1106 GNUNET_TESTBED_operation_queue_insert_ (struct OperationQueue *queue,
1107                                         struct GNUNET_TESTBED_Operation *op)
1108 {
1109   return GNUNET_TESTBED_operation_queue_insert2_ (queue, op, 1);
1110 }
1111
1112
1113 /**
1114  * Marks the given operation as waiting on the queues.  Once all queues permit
1115  * the operation to become active, the operation will be activated.  The actual
1116  * activation will occur in a separate task (thus allowing multiple queue
1117  * insertions to be made without having the first one instantly trigger the
1118  * operation if the first queue has sufficient resources).
1119  *
1120  * @param op the operation to marks as waiting
1121  */
1122 void
1123 GNUNET_TESTBED_operation_begin_wait_ (struct GNUNET_TESTBED_Operation *op)
1124 {
1125   GNUNET_assert (NULL == op->rq_entry);
1126   change_state (op, OP_STATE_WAITING);
1127   (void) check_readiness (op);
1128 }
1129
1130
1131 /**
1132  * Marks an active operation as inactive - the operation will be kept in a
1133  * ready-to-be-released state and continues to hold resources until another
1134  * operation contents for them.
1135  *
1136  * @param op the operation to be marked as inactive.  The operation start
1137  *          callback should have been called before for this operation to mark
1138  *          it as inactive.
1139  */
1140 void
1141 GNUNET_TESTBED_operation_inactivate_ (struct GNUNET_TESTBED_Operation *op)
1142 {
1143   struct OperationQueue **queues;
1144   size_t ms;
1145   unsigned int nqueues;
1146   unsigned int i;
1147
1148   GNUNET_assert (OP_STATE_ACTIVE == op->state);
1149   change_state (op, OP_STATE_INACTIVE);
1150   nqueues = op->nqueues;
1151   ms = sizeof (struct OperationQueue *) * nqueues;
1152   queues = GNUNET_malloc (ms);
1153   /* Cloning is needed as the operation be released by waiting operations and
1154      hence its nqueues memory ptr will be freed */
1155   GNUNET_assert (NULL != (queues = memcpy (queues, op->queues, ms)));
1156   for (i = 0; i < nqueues; i++)
1157     recheck_waiting (queues[i]);
1158   GNUNET_free (queues);
1159 }
1160
1161
1162 /**
1163  * Marks and inactive operation as active.  This fuction should be called to
1164  * ensure that the oprelease callback will not be called until it is either
1165  * marked as inactive or released.
1166  *
1167  * @param op the operation to be marked as active
1168  */
1169 void
1170 GNUNET_TESTBED_operation_activate_ (struct GNUNET_TESTBED_Operation *op)
1171 {
1172
1173   GNUNET_assert (OP_STATE_INACTIVE == op->state);
1174   change_state (op, OP_STATE_ACTIVE);
1175 }
1176
1177
1178 /**
1179  * An operation is 'done' (was cancelled or finished); remove
1180  * it from the queues and release associated resources.
1181  *
1182  * @param op operation that finished
1183  */
1184 void
1185 GNUNET_TESTBED_operation_release_ (struct GNUNET_TESTBED_Operation *op)
1186 {
1187   struct QueueEntry *entry;  
1188   struct OperationQueue *opq;
1189   unsigned int i;
1190
1191   if (OP_STATE_INIT == op->state)
1192   {
1193     GNUNET_free (op);
1194     return;
1195   }
1196   if (OP_STATE_READY == op->state)
1197     rq_remove (op);
1198   if (OP_STATE_INACTIVE == op->state) /* Activate the operation if inactive */
1199     GNUNET_TESTBED_operation_activate_ (op);
1200   if (OP_STATE_ACTIVE == op->state)
1201     update_tslots (op);
1202   GNUNET_assert (NULL != op->queues);
1203   GNUNET_assert (NULL != op->qentries);  
1204   for (i = 0; i < op->nqueues; i++)
1205   {
1206     entry = op->qentries[i];
1207     remove_queue_entry (op, i);
1208     opq = op->queues[i];
1209     switch (op->state)
1210     {      
1211     case OP_STATE_INIT:
1212     case OP_STATE_INACTIVE:
1213       GNUNET_assert (0);
1214       break;
1215     case OP_STATE_WAITING:      
1216       break;
1217     case OP_STATE_ACTIVE:
1218     case OP_STATE_READY:
1219       GNUNET_assert (0 != opq->active);
1220       GNUNET_assert (opq->active >= entry->nres);
1221       opq->active -= entry->nres;
1222       recheck_waiting (opq);
1223       break;
1224     }    
1225     GNUNET_free (entry);
1226   }
1227   GNUNET_free_non_null (op->qentries);
1228   GNUNET_free (op->queues);
1229   GNUNET_free (op->nres);
1230   if (NULL != op->release)
1231     op->release (op->cb_cls);
1232   GNUNET_free (op);
1233 }
1234
1235
1236 /**
1237  * Marks an operation as failed
1238  *
1239  * @param op the operation to be marked as failed
1240  */
1241 void
1242 GNUNET_TESTBED_operation_mark_failed (struct GNUNET_TESTBED_Operation *op)
1243 {
1244   op->failed = GNUNET_YES;
1245 }
1246
1247
1248 /* end of testbed_api_operations.c */