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