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