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