Merge branch 'master' of ssh://gnunet.org/gnunet
[oweals/gnunet.git] / src / ats / plugin_ats_ril.c
1 /*
2  This file is part of GNUnet.
3  Copyright (C) 2011-2014 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
19 /**
20  * @file ats/plugin_ats_ril.c
21  * @brief ATS reinforcement learning solver
22  * @author Fabian Oehlmann
23  * @author Matthias Wachs
24  */
25 #include "platform.h"
26 #include <float.h>
27 #include <math.h>
28 #include "gnunet_ats_plugin.h"
29 #include "gnunet-service-ats_addresses.h"
30
31
32
33 #define LOG(kind,...) GNUNET_log_from (kind, "ats-ril",__VA_ARGS__)
34
35 #define RIL_MIN_BW                      (5 * ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__))
36 #define RIL_MAX_BW                      GNUNET_ATS_MaxBandwidth
37
38 #define RIL_ACTION_INVALID              -1
39 #define RIL_INTERVAL_EXPONENT           10
40 #define RIL_UTILITY_DELAY_MAX           1000
41
42 #define RIL_DEFAULT_STEP_TIME_MIN       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 200)
43 #define RIL_DEFAULT_STEP_TIME_MAX       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 2000)
44 #define RIL_DEFAULT_ALGORITHM           RIL_ALGO_SARSA
45 #define RIL_DEFAULT_SELECT              RIL_SELECT_SOFTMAX
46 #define RIL_DEFAULT_WELFARE             RIL_WELFARE_NASH
47 #define RIL_DEFAULT_DISCOUNT_BETA       0.6
48 #define RIL_DEFAULT_DISCOUNT_GAMMA      0.5
49 #define RIL_DEFAULT_GRADIENT_STEP_SIZE  0.01
50 #define RIL_DEFAULT_TRACE_DECAY         0.5
51 #define RIL_DEFAULT_EXPLORE_RATIO       1
52 #define RIL_DEFAULT_EXPLORE_DECAY       0.95
53 #define RIL_DEFAULT_RBF_DIVISOR         50
54 #define RIL_DEFAULT_TEMPERATURE         0.1
55 #define RIL_DEFAULT_TEMPERATURE_DECAY   1
56
57 #define RIL_INC_DEC_STEP_SIZE           1
58 #define RIL_NOP_DECAY                   0.5
59
60 /**
61  * ATS reinforcement learning solver
62  *
63  * General description
64  */
65
66 /**
67  * The actions, how an agent can manipulate the current assignment. I.e. how the bandwidth can be
68  * changed for the currently chosen address. Not depicted in the enum are the actions of switching
69  * to a particular address. The action of switching to address with index i is depicted by the
70  * number (RIL_ACTION_TYPE_NUM + i).
71  */
72 enum RIL_Action_Type
73 {
74   RIL_ACTION_NOTHING = 0,
75   RIL_ACTION_BW_IN_DBL = -2, //TODO? Potentially add more actions
76   RIL_ACTION_BW_IN_HLV = -3,
77   RIL_ACTION_BW_IN_INC = 1,
78   RIL_ACTION_BW_IN_DEC = 2,
79   RIL_ACTION_BW_OUT_DBL = -4,
80   RIL_ACTION_BW_OUT_HLV = -5,
81   RIL_ACTION_BW_OUT_INC = 3,
82   RIL_ACTION_BW_OUT_DEC = 4,
83   RIL_ACTION_TYPE_NUM = 5
84 };
85
86 enum RIL_Algorithm
87 {
88   RIL_ALGO_SARSA = 0,
89   RIL_ALGO_Q = 1
90 };
91
92 enum RIL_Select
93 {
94   RIL_SELECT_SOFTMAX = 0,
95   RIL_SELECT_EGREEDY = 1
96 };
97
98 enum RIL_Welfare
99 {
100   RIL_WELFARE_NASH,
101   RIL_WELFARE_EGALITARIAN
102 };
103
104 enum RIL_E_Modification
105 {
106   RIL_E_DECAY,
107   RIL_E_ZERO,
108   RIL_E_ACCUMULATE,
109   RIL_E_REPLACE
110 };
111
112 /**
113  * Global learning parameters
114  */
115 struct RIL_Learning_Parameters
116 {
117   /**
118    * The TD-algorithm to use
119    */
120   enum RIL_Algorithm algorithm;
121
122   /**
123    * Gradient-descent step-size
124    */
125   double alpha;
126
127   /**
128    * Learning discount variable in the TD-update for semi-MDPs
129    */
130   double beta;
131
132   /**
133    * Learning discount factor in the TD-update for MDPs
134    */
135   double gamma;
136
137   /**
138    * Trace-decay factor for eligibility traces
139    */
140   double lambda;
141
142   /**
143    * Whether to accumulate or replace eligibility traces
144    */
145   enum RIL_E_Modification eligibility_trace_mode;
146
147   /**
148    * Initial softmax action-selection temperature
149    */
150   double temperature_init;
151
152   /**
153    * Softmax action-selection temperature
154    */
155   double temperature;
156
157   /**
158    * Decay factor of the temperature value
159    */
160   double temperature_decay;
161
162   /**
163    * Which measure of social welfare should be used
164    */
165   enum RIL_Welfare social_welfare;
166
167   /**
168    * State space divisor
169    */
170   unsigned long long rbf_divisor;
171
172   /**
173    * Action selection strategy;
174    */
175   enum RIL_Select select;
176
177   /**
178    * Initial exploration ratio value
179    */
180   double epsilon_init;
181
182   /**
183    * Ratio, with what probability an agent should explore in the e-greed policy
184    */
185   double epsilon;
186
187   /**
188    * Decay factor of the explore ratio
189    */
190   double epsilon_decay;
191
192   /**
193    * Minimal interval time between steps in milliseconds
194    */
195   struct GNUNET_TIME_Relative step_time_min;
196
197   /**
198    * Maximum interval time between steps in milliseconds
199    */
200   struct GNUNET_TIME_Relative step_time_max;
201 };
202
203 /**
204  * Wrapper for addresses to store them in agent's linked list
205  */
206 struct RIL_Address_Wrapped
207 {
208   /**
209    * Next in DLL
210    */
211   struct RIL_Address_Wrapped *next;
212
213   /**
214    * Previous in DLL
215    */
216   struct RIL_Address_Wrapped *prev;
217
218   /**
219    * The address
220    */
221   struct ATS_Address *address_naked;
222 };
223
224
225 struct RIL_Peer_Agent
226 {
227   /**
228    * Next agent in solver's linked list
229    */
230   struct RIL_Peer_Agent *next;
231
232   /**
233    * Previous agent in solver's linked list
234    */
235   struct RIL_Peer_Agent *prev;
236
237   /**
238    * Environment handle
239    */
240   struct GAS_RIL_Handle *envi;
241
242   /**
243    * Peer ID
244    */
245   struct GNUNET_PeerIdentity peer;
246
247   /**
248    * Whether the agent is active or not
249    */
250   int is_active;
251
252   /**
253    * Number of performed time-steps
254    */
255   unsigned long long step_count;
256
257   /**
258    * Experience matrix W
259    */
260   double ** W;
261
262   /**
263    * Number of rows of W / Number of state-vector features
264    */
265   unsigned int m;
266
267   /**
268    * Number of columns of W / Number of actions
269    */
270   unsigned int n;
271
272   /**
273    * Last perceived state feature vector
274    */
275   double *s_old;
276
277   /**
278    * Last chosen action
279    */
280   int a_old;
281
282   /**
283    * Eligibility traces
284    */
285   double ** E;
286
287   /**
288    * Whether to reset the eligibility traces to 0 after a Q-exploration step
289    */
290   int eligibility_reset;
291
292   /**
293    * Address in use
294    */
295   struct ATS_Address *address_inuse;
296
297   /**
298    * Head of addresses DLL
299    */
300   struct RIL_Address_Wrapped *addresses_head;
301
302   /**
303    * Tail of addresses DLL
304    */
305   struct RIL_Address_Wrapped *addresses_tail;
306
307   /**
308    * Inbound bandwidth assigned by the agent
309    */
310   uint32_t bw_in;
311
312   /**
313    * Outbound bandwidth assigned by the agent
314    */
315   uint32_t bw_out;
316
317   /**
318    * Flag whether a suggestion has to be issued
319    */
320   int suggestion_issue;
321
322   /**
323    * The address which has to be issued
324    */
325   struct ATS_Address *suggestion_address;
326
327   /**
328    * The agent's last objective value
329    */
330   double objective_old;
331
332   /**
333    * NOP bonus
334    */
335   double nop_bonus;
336 };
337
338 struct RIL_Scope
339 {
340   /**
341    * ATS network type
342    */
343   enum GNUNET_ATS_Network_Type type;
344
345   /**
346    * Total available inbound bandwidth
347    */
348   uint32_t bw_in_available;
349
350   /**
351    * Bandwidth inbound assigned in network after last step
352    */
353   uint32_t bw_in_assigned;
354
355   /**
356    * Bandwidth inbound actually utilized in the network
357    */
358   uint32_t bw_in_utilized;
359
360   /**
361    * Total available outbound bandwidth
362    */
363   uint32_t bw_out_available;
364
365   /**
366    * Bandwidth outbound assigned in network after last step
367    */
368   unsigned long long bw_out_assigned;
369
370   /**
371    * Bandwidth outbound actually utilized in the network
372    */
373   unsigned long long bw_out_utilized;
374
375   /**
376    * Number of active agents in scope
377    */
378   unsigned int active_agent_count;
379
380   /**
381    * The social welfare achieved in the scope
382    */
383   double social_welfare;
384 };
385
386 /**
387  * A handle for the reinforcement learning solver
388  */
389 struct GAS_RIL_Handle
390 {
391   /**
392    * The solver-plugin environment of the solver-plugin API
393    */
394   struct GNUNET_ATS_PluginEnvironment *env;
395
396   /**
397    * Number of performed steps
398    */
399   unsigned long long step_count;
400
401   /**
402    * Timestamp for the last time-step
403    */
404   struct GNUNET_TIME_Absolute step_time_last;
405
406   /**
407    * Task identifier of the next time-step to be executed
408    */
409   struct GNUNET_SCHEDULER_Task * step_next_task_id;
410
411   /**
412    * Variable discount factor, dependent on time between steps
413    */
414   double global_discount_variable;
415
416   /**
417    * Integrated variable discount factor, dependent on time between steps
418    */
419   double global_discount_integrated;
420
421   /**
422    * Lock for bulk operations
423    */
424   int bulk_lock;
425
426   /**
427    * Number of changes during a lock
428    */
429   int bulk_changes;
430
431   /**
432    * Learning parameters
433    */
434   struct RIL_Learning_Parameters parameters;
435
436   /**
437    * Array of networks with global assignment state
438    */
439   struct RIL_Scope * network_entries;
440
441   /**
442    * Networks count
443    */
444   unsigned int networks_count;
445
446   /**
447    * List of active peer-agents
448    */
449   struct RIL_Peer_Agent * agents_head;
450   struct RIL_Peer_Agent * agents_tail;
451
452   /**
453    * Shutdown
454    */
455   int done;
456
457   /**
458    * Simulate steps, i.e. schedule steps immediately
459    */
460   unsigned long long simulate;
461 };
462
463 /*
464  *  "Private" functions
465  *  ---------------------------
466  */
467
468 /**
469  * Estimate the current action-value for state s and action a
470  *
471  * @param agent agent performing the estimation
472  * @param state s
473  * @param action a
474  * @return estimation value
475  */
476 static double
477 agent_q (struct RIL_Peer_Agent *agent,
478          const double *state,
479          int action)
480 {
481   unsigned int i;
482   double result = 0.0;
483
484   for (i = 0; i < agent->m; i++)
485     result += state[i] * agent->W[action][i];
486
487   /* prevent crashes if learning diverges */
488   if (isnan(result))
489       return isnan(result) * UINT32_MAX;
490   if (isinf(result))
491     return isinf(result) * UINT32_MAX;
492   return result;
493 }
494
495
496 /**
497  * Get the index of the address in the agent's list.
498  *
499  * @param agent agent handle
500  * @param address address handle
501  * @return the index, starting with zero
502  */
503 static int
504 agent_address_get_index (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
505 {
506   int i;
507   struct RIL_Address_Wrapped *cur;
508
509   i = -1;
510   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
511   {
512     i++;
513     if (cur->address_naked == address)
514       return i;
515   }
516   return i;
517 }
518
519
520 /**
521  * Gets the wrapped address from the agent's list
522  *
523  * @param agent agent handle
524  * @param address address handle
525  * @return wrapped address
526  */
527 static struct RIL_Address_Wrapped *
528 agent_address_get_wrapped (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
529 {
530   struct RIL_Address_Wrapped *cur;
531
532   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
533     if (cur->address_naked == address)
534       return cur;
535   return NULL;
536 }
537
538
539 static int
540 agent_action_is_possible (struct RIL_Peer_Agent *agent, int action)
541 {
542   int address_index;
543
544   switch (action)
545   {
546   case RIL_ACTION_NOTHING:
547     return GNUNET_YES;
548     break;
549   case RIL_ACTION_BW_IN_INC:
550   case RIL_ACTION_BW_IN_DBL:
551     if (agent->bw_in >= RIL_MAX_BW)
552       return GNUNET_NO;
553     else
554       return GNUNET_YES;
555     break;
556   case RIL_ACTION_BW_IN_DEC:
557   case RIL_ACTION_BW_IN_HLV:
558     if (agent->bw_in <= 0)
559       return GNUNET_NO;
560     else
561       return GNUNET_YES;
562     break;
563   case RIL_ACTION_BW_OUT_INC:
564   case RIL_ACTION_BW_OUT_DBL:
565     if (agent->bw_out >= RIL_MAX_BW)
566       return GNUNET_NO;
567     else
568       return GNUNET_YES;
569     break;
570   case RIL_ACTION_BW_OUT_DEC:
571   case RIL_ACTION_BW_OUT_HLV:
572     if (agent->bw_out <= 0)
573       return GNUNET_NO;
574     else
575       return GNUNET_YES;
576     break;
577   default:
578     if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action
579     {
580       address_index = action - RIL_ACTION_TYPE_NUM;
581
582       GNUNET_assert(address_index >= 0);
583       GNUNET_assert(
584           address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked));
585
586       if ((agent_address_get_index(agent, agent->address_inuse) == address_index) ||
587           agent->address_inuse->active)
588         return GNUNET_NO;
589       else
590         return GNUNET_YES;
591       break;
592     }
593     // error - action does not exist
594     GNUNET_assert(GNUNET_NO);
595   }
596 }
597
598
599 /**
600  * Gets the action, with the maximal estimated Q-value (i.e. the one currently estimated to bring the
601  * most reward in the future)
602  *
603  * @param agent agent performing the calculation
604  * @param state the state from which to take the action
605  * @return the action promising most future reward
606  */
607 static int
608 agent_get_action_max (struct RIL_Peer_Agent *agent, double *state)
609 {
610   int i;
611   int max_i = RIL_ACTION_INVALID;
612   double cur_q;
613   double max_q = -DBL_MAX;
614
615   for (i = 0; i < agent->n; i++)
616   {
617     if (agent_action_is_possible(agent, i))
618     {
619       cur_q = agent_q (agent, state, i);
620       if (cur_q > max_q)
621       {
622         max_q = cur_q;
623         max_i = i;
624       }
625     }
626   }
627
628   GNUNET_assert(RIL_ACTION_INVALID != max_i);
629
630   return max_i;
631 }
632
633 /**
634  * Chooses a random action from the set of possible ones
635  *
636  * @param agent the agent performing the action
637  * @return the action index
638  */
639 static int
640 agent_get_action_random (struct RIL_Peer_Agent *agent)
641 {
642   int i;
643   int is_possible[agent->n];
644   int sum = 0;
645   int r;
646
647   for (i = 0; i<agent->n; i++)
648   {
649     if (agent_action_is_possible(agent, i))
650     {
651       is_possible[i] = GNUNET_YES;
652       sum++;
653     }
654     else
655     {
656       is_possible[i] = GNUNET_NO;
657     }
658   }
659
660   r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, sum);
661
662   sum = -1;
663   for (i = 0; i<agent->n; i++)
664   {
665     if (is_possible[i])
666     {
667       sum++;
668       if (sum == r)
669         return i;
670     }
671   }
672
673   GNUNET_assert(GNUNET_NO);
674   return RIL_ACTION_INVALID;
675 }
676
677
678 /**
679  * Updates the weights (i.e. coefficients) of the weight vector in matrix W for action a
680  *
681  * @param agent the agent performing the update
682  * @param reward the reward received for the last action
683  * @param s_next the new state, the last step got the agent into
684  * @param a_prime the new
685  */
686 static void
687 agent_update (struct RIL_Peer_Agent *agent, double reward, double *s_next, int a_prime)
688 {
689   int i;
690   int k;
691   double delta;
692   double **theta = agent->W;
693
694   delta = agent->envi->global_discount_integrated * reward; //reward
695   delta += agent->envi->global_discount_variable * agent_q (agent, s_next, a_prime); //discounted future value
696   delta -= agent_q (agent, agent->s_old, agent->a_old); //one step
697
698 //  LOG(GNUNET_ERROR_TYPE_INFO, "update()   Step# %llu  Q(s,a): %f  a: %f  r: %f  y: %f  Q(s+1,a+1) = %f  delta: %f\n",
699 //      agent->step_count,
700 //      agent_q (agent, agent->s_old, agent->a_old),
701 //      agent->envi->parameters.alpha,
702 //      reward,
703 //      agent->envi->global_discount_variable,
704 //      agent_q (agent, s_next, a_prime),
705 //      delta);
706
707   for (k = 0; k < agent->n; k++)
708   {
709     for (i = 0; i < agent->m; i++)
710     {
711   //    LOG(GNUNET_ERROR_TYPE_INFO, "alpha = %f   delta = %f   e[%d] = %f\n",
712   //        agent->envi->parameters.alpha,
713   //        delta,
714   //        i,
715   //        agent->e[i]);
716       theta[k][i] += agent->envi->parameters.alpha * delta * agent->E[k][i];
717     }
718   }
719 }
720
721
722 /**
723  * Changes the eligibility trace vector e in various manners:
724  * #RIL_E_ACCUMULATE - adds @a feature to each component as in accumulating eligibility traces
725  * #RIL_E_REPLACE - resets each component to @a feature  as in replacing traces
726  * #RIL_E_DECAY - multiplies e with discount factor and lambda as in the update rule
727  * #RIL_E_ZERO - sets e to 0 as in Watkin's Q-learning algorithm when exploring and when initializing
728  *
729  * @param agent the agent handle
730  * @param mod the kind of modification
731  * @param feature the feature vector
732  * @param action the action to take
733  */
734 static void
735 agent_modify_eligibility (struct RIL_Peer_Agent *agent,
736                           enum RIL_E_Modification mod,
737                           double *feature,
738                           int action)
739 {
740   int i;
741   int k;
742
743   for (i = 0; i < agent->m; i++)
744   {
745     switch (mod)
746     {
747     case RIL_E_ACCUMULATE:
748       agent->E[action][i] += feature[i];
749       break;
750     case RIL_E_REPLACE:
751       agent->E[action][i] = agent->E[action][i] > feature[i] ? agent->E[action][i] : feature[i];
752       break;
753     case RIL_E_DECAY:
754       for (k = 0; k < agent->n; k++)
755       {
756         agent->E[k][i] *= agent->envi->global_discount_variable * agent->envi->parameters.lambda;
757       }
758       break;
759     case RIL_E_ZERO:
760       for (k = 0; k < agent->n; k++)
761       {
762         agent->E[k][i] = 0;
763       }
764       break;
765     }
766   }
767 }
768
769 /**
770  * Informs the environment about the status of the solver
771  *
772  * @param solver
773  * @param op
774  * @param stat
775  */
776 static void
777 ril_inform (struct GAS_RIL_Handle *solver,
778             enum GAS_Solver_Operation op,
779             enum GAS_Solver_Status stat)
780 {
781   solver->env->info_cb (solver->env->cls,
782                         op,
783                         stat,
784                         GAS_INFO_NONE);
785 }
786
787 /**
788  * Calculates the maximum bandwidth an agent can assign in a network scope
789  *
790  * @param net
791  */
792 static unsigned long long
793 ril_get_max_bw (struct RIL_Scope *net)
794 {
795   return GNUNET_MIN(2 * GNUNET_MAX(net->bw_in_available, net->bw_out_available), GNUNET_ATS_MaxBandwidth);
796 }
797
798 /**
799  * Changes the active assignment suggestion of the handler and invokes the bw_changed callback to
800  * notify ATS of its new decision
801  *
802  * @param solver solver handle
803  * @param agent agent handle
804  * @param new_address the address which is to be used
805  * @param new_bw_in the new amount of inbound bandwidth set for this address
806  * @param new_bw_out the new amount of outbound bandwidth set for this address
807  * @param silent disables invocation of the bw_changed callback, if #GNUNET_YES
808  */
809 static void
810 envi_set_active_suggestion (struct GAS_RIL_Handle *solver,
811     struct RIL_Peer_Agent *agent,
812     struct ATS_Address *new_address,
813     unsigned long long new_bw_in,
814     unsigned long long new_bw_out,
815     int silent)
816 {
817   int notify = GNUNET_NO;
818
819   LOG(GNUNET_ERROR_TYPE_DEBUG,
820       "    set_active_suggestion() for peer '%s'\n",
821       GNUNET_i2s (&agent->peer));
822
823   //address change
824   if (agent->address_inuse != new_address)
825   {
826     if (NULL != agent->address_inuse)
827     {
828       agent->address_inuse->active = GNUNET_NO;
829       agent->address_inuse->assigned_bw_in = 0;
830       agent->address_inuse->assigned_bw_out = 0;
831     }
832     if (NULL != new_address)
833     {
834       LOG(GNUNET_ERROR_TYPE_DEBUG, "    set address active: %s\n", agent->is_active ? "yes" : "no");
835       new_address->active = agent->is_active;
836       new_address->assigned_bw_in = agent->bw_in;
837       new_address->assigned_bw_out = agent->bw_out;
838     }
839     notify |= GNUNET_YES;
840   }
841
842   if (new_address)
843   {
844     //activity change
845     if (new_address->active != agent->is_active)
846     {
847       new_address->active = agent->is_active;
848       notify |= GNUNET_YES;
849     }
850
851     //bw change
852     if (agent->bw_in != new_bw_in)
853     {
854       agent->bw_in = new_bw_in;
855       new_address->assigned_bw_in = new_bw_in;
856       notify |= GNUNET_YES;
857     }
858     if (agent->bw_out != new_bw_out)
859     {
860       agent->bw_out = new_bw_out;
861       new_address->assigned_bw_out = new_bw_out;
862       notify |= GNUNET_YES;
863     }
864   }
865
866   if (notify && agent->is_active && (GNUNET_NO == silent))
867   {
868     if (new_address)
869     {
870       LOG(GNUNET_ERROR_TYPE_DEBUG, "    envi_set_active_suggestion() notify\n");
871       agent->suggestion_issue = GNUNET_YES;
872       agent->suggestion_address = new_address;
873     }
874     else if (agent->address_inuse)
875     {
876       /* disconnect case, no new address */
877       GNUNET_assert(0 ==  agent->address_inuse->assigned_bw_in);
878       GNUNET_assert(0 == agent->address_inuse->assigned_bw_out);
879       agent->bw_in = 0;
880       agent->bw_out = 0;
881
882       agent->suggestion_issue = GNUNET_YES;
883       agent->suggestion_address = agent->address_inuse;
884     }
885   }
886   agent->address_inuse = new_address;
887 }
888
889
890 /**
891  * Allocates a state vector and fills it with the features present
892  * @param solver the solver handle
893  * @param agent the agent handle
894  * @return pointer to the state vector
895  */
896 static double *
897 envi_get_state (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
898 {
899   double *state;
900   double y[2];
901   double x[2];
902   double d[2];
903   double sigma;
904   double f;
905   int m;
906   int i;
907   int k;
908   unsigned long long max_bw;
909
910   state = GNUNET_malloc (sizeof(double) * agent->m);
911
912   max_bw = ril_get_max_bw((struct RIL_Scope *) agent->address_inuse->solver_information);
913
914   y[0] = (double) agent->bw_out;
915   y[1] = (double) agent->bw_in;
916
917   m = agent_address_get_index (agent, agent->address_inuse) * (solver->parameters.rbf_divisor+1) * (solver->parameters.rbf_divisor+1);
918   for (i = 0; i <= solver->parameters.rbf_divisor; i++)
919   {
920     for (k = 0; k <= solver->parameters.rbf_divisor; k++)
921     {
922       x[0] = (double) i * (double) max_bw / (double) solver->parameters.rbf_divisor;
923       x[1] = (double) k * (double) max_bw / (double) solver->parameters.rbf_divisor;
924       d[0] = x[0]-y[0];
925       d[1] = x[1]-y[1];
926       sigma = (((double) max_bw / ((double) solver->parameters.rbf_divisor + 1)) * 0.5);
927       f = exp(-((d[0]*d[0] + d[1]*d[1]) / (2 * sigma * sigma)));
928       state[m++] = f;
929     }
930   }
931
932   return state;
933 }
934
935
936 /**
937  * Returns the utility value of the connection an agent manages
938  *
939  * @param agent the agent in question
940  * @return the utility value
941  */
942 static double
943 agent_get_utility (struct RIL_Peer_Agent *agent)
944 {
945   const double *preferences;
946   double delay_atsi;
947   double delay_norm;
948   double pref_match;
949
950   preferences = agent->envi->env->get_preferences (agent->envi->env->cls,
951                                                    &agent->peer);
952
953   delay_atsi = agent->address_inuse->norm_delay.norm;
954   delay_norm = RIL_UTILITY_DELAY_MAX*exp(-delay_atsi*0.00001);
955
956   pref_match = preferences[GNUNET_ATS_PREFERENCE_LATENCY] * delay_norm;
957   pref_match += preferences[GNUNET_ATS_PREFERENCE_BANDWIDTH] *
958       sqrt((double) (agent->bw_in/RIL_MIN_BW) * (double) (agent->bw_out/RIL_MIN_BW));
959   return pref_match;
960 }
961
962 /**
963  * Calculates the social welfare within a network scope according to what social
964  * welfare measure is set in the configuration.
965  *
966  * @param solver the solver handle
967  * @param scope the network scope in question
968  * @return the social welfare value
969  */
970 static double
971 ril_network_get_social_welfare (struct GAS_RIL_Handle *solver, struct RIL_Scope *scope)
972 {
973   struct RIL_Peer_Agent *cur;
974   double result;
975
976   switch (solver->parameters.social_welfare)
977   {
978   case RIL_WELFARE_EGALITARIAN:
979     result = DBL_MAX;
980     for (cur = solver->agents_head; NULL != cur; cur = cur->next)
981     {
982       if (cur->is_active && cur->address_inuse && (cur->address_inuse->solver_information == scope))
983       {
984         result = GNUNET_MIN(result, agent_get_utility(cur));
985       }
986     }
987     return result;
988
989   case RIL_WELFARE_NASH:
990     result = 0;
991     for (cur = solver->agents_head; NULL != cur; cur = cur->next)
992     {
993       if (cur->is_active && cur->address_inuse && (cur->address_inuse->solver_information == scope))
994       {
995         result *= pow(agent_get_utility(cur), 1.0 / (double) scope->active_agent_count);
996       }
997     }
998     return result;
999   }
1000   GNUNET_assert(GNUNET_NO);
1001   return 1;
1002 }
1003
1004 static double
1005 envi_get_penalty (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
1006 {
1007   struct RIL_Scope *net;
1008   unsigned long long over_max;
1009   unsigned long long over_in = 0;
1010   unsigned long long over_out = 0;
1011
1012   net = agent->address_inuse->solver_information;
1013
1014   if (net->bw_in_utilized > net->bw_in_available)
1015   {
1016     over_in = net->bw_in_utilized - net->bw_in_available;
1017     if (RIL_ACTION_BW_IN_INC == agent->a_old)
1018     {
1019       /* increase quadratically */
1020       over_in *= over_in;
1021     }
1022   }
1023   if (net->bw_out_utilized > net->bw_out_available)
1024   {
1025     over_out = net->bw_out_utilized - net->bw_out_available;
1026     if (RIL_ACTION_BW_OUT_INC == agent->a_old)
1027     {
1028       /* increase quadratically */
1029       over_out *= over_out;
1030     }
1031   }
1032   over_max = (over_in + over_out) / (RIL_MIN_BW * RIL_MIN_BW);
1033
1034   return -1.0 * (double) over_max;
1035 }
1036
1037 /**
1038  * Gets the reward for the last performed step, which is calculated in equal
1039  * parts from the local (the peer specific) and the global (for all peers
1040  * identical) reward.
1041  *
1042  * @param solver the solver handle
1043  * @param agent the agent handle
1044  * @return the reward
1045  */
1046 static double
1047 envi_get_reward (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
1048 {
1049   struct RIL_Scope *net;
1050   double objective;
1051   double delta;
1052   double steady;
1053   double penalty;
1054   double reward;
1055
1056   net = agent->address_inuse->solver_information;
1057
1058   penalty = envi_get_penalty(solver, agent);
1059   objective = (agent_get_utility (agent) + net->social_welfare) / 2;
1060   delta = objective - agent->objective_old;
1061   agent->objective_old = objective;
1062
1063   if (delta != 0 && penalty == 0)
1064   {
1065     agent->nop_bonus = delta * RIL_NOP_DECAY;
1066   }
1067   else
1068   {
1069     agent->nop_bonus *= RIL_NOP_DECAY;
1070   }
1071
1072   steady = (RIL_ACTION_NOTHING == agent->a_old) ? agent->nop_bonus : 0;
1073
1074   reward = delta + steady;
1075   return reward + penalty;
1076 }
1077
1078 /**
1079  * Doubles the bandwidth for the active address
1080  *
1081  * @param solver solver handle
1082  * @param agent agent handle
1083  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise the outbound bandwidth
1084  */
1085 static void
1086 envi_action_bw_double (struct GAS_RIL_Handle *solver,
1087     struct RIL_Peer_Agent *agent,
1088     int direction_in)
1089 {
1090   unsigned long long new_bw;
1091   unsigned long long max_bw;
1092
1093   max_bw = ril_get_max_bw((struct RIL_Scope *) agent->address_inuse->solver_information);
1094
1095   if (direction_in)
1096   {
1097     new_bw = agent->bw_in * 2;
1098     if (new_bw < agent->bw_in || new_bw > max_bw)
1099       new_bw = max_bw;
1100     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw,
1101         agent->bw_out, GNUNET_NO);
1102   }
1103   else
1104   {
1105     new_bw = agent->bw_out * 2;
1106     if (new_bw < agent->bw_out || new_bw > max_bw)
1107       new_bw = max_bw;
1108     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
1109         new_bw, GNUNET_NO);
1110   }
1111 }
1112
1113 /**
1114  * Cuts the bandwidth for the active address in half. The least amount of bandwidth suggested, is
1115  * the minimum bandwidth for a peer, in order to not invoke a disconnect.
1116  *
1117  * @param solver solver handle
1118  * @param agent agent handle
1119  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
1120  * bandwidth
1121  */
1122 static void
1123 envi_action_bw_halven (struct GAS_RIL_Handle *solver,
1124     struct RIL_Peer_Agent *agent,
1125     int direction_in)
1126 {
1127   unsigned long long new_bw;
1128
1129   if (direction_in)
1130   {
1131     new_bw = agent->bw_in / 2;
1132     if (new_bw <= 0 || new_bw > agent->bw_in)
1133       new_bw = 0;
1134     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
1135         GNUNET_NO);
1136   }
1137   else
1138   {
1139     new_bw = agent->bw_out / 2;
1140     if (new_bw <= 0 || new_bw > agent->bw_out)
1141       new_bw = 0;
1142     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
1143         GNUNET_NO);
1144   }
1145 }
1146
1147 /**
1148  * Increases the bandwidth by 5 times the minimum bandwidth for the active address.
1149  *
1150  * @param solver solver handle
1151  * @param agent agent handle
1152  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
1153  * bandwidth
1154  */
1155 static void
1156 envi_action_bw_inc (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
1157 {
1158   unsigned long long new_bw;
1159   unsigned long long max_bw;
1160
1161   max_bw = ril_get_max_bw((struct RIL_Scope *) agent->address_inuse->solver_information);
1162
1163   if (direction_in)
1164   {
1165     new_bw = agent->bw_in + (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW);
1166     if (new_bw < agent->bw_in || new_bw > max_bw)
1167       new_bw = max_bw;
1168     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw,
1169         agent->bw_out, GNUNET_NO);
1170   }
1171   else
1172   {
1173     new_bw = agent->bw_out + (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW);
1174     if (new_bw < agent->bw_out || new_bw > max_bw)
1175       new_bw = max_bw;
1176     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
1177         new_bw, GNUNET_NO);
1178   }
1179 }
1180
1181 /**
1182  * Decreases the bandwidth by 5 times the minimum bandwidth for the active address. The least amount
1183  * of bandwidth suggested, is the minimum bandwidth for a peer, in order to not invoke a disconnect.
1184  *
1185  * @param solver solver handle
1186  * @param agent agent handle
1187  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
1188  * bandwidth
1189  */
1190 static void
1191 envi_action_bw_dec (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
1192 {
1193   unsigned long long new_bw;
1194
1195   if (direction_in)
1196   {
1197     new_bw = agent->bw_in - (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW);
1198     if (new_bw <= 0 || new_bw > agent->bw_in)
1199       new_bw = 0;
1200     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
1201         GNUNET_NO);
1202   }
1203   else
1204   {
1205     new_bw = agent->bw_out - (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW);
1206     if (new_bw <= 0 || new_bw > agent->bw_out)
1207       new_bw = 0;
1208     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
1209         GNUNET_NO);
1210   }
1211 }
1212
1213 /**
1214  * Switches to the address given by its index
1215  *
1216  * @param solver solver handle
1217  * @param agent agent handle
1218  * @param address_index index of the address as it is saved in the agent's list, starting with zero
1219  */
1220 static void
1221 envi_action_address_switch (struct GAS_RIL_Handle *solver,
1222     struct RIL_Peer_Agent *agent,
1223     unsigned int address_index)
1224 {
1225   struct RIL_Address_Wrapped *cur;
1226   int i = 0;
1227
1228   //cur = agent_address_get_wrapped(agent, agent->address_inuse);
1229
1230   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
1231   {
1232     if (i == address_index)
1233     {
1234       envi_set_active_suggestion (solver, agent, cur->address_naked, agent->bw_in, agent->bw_out,
1235           GNUNET_NO);
1236       return;
1237     }
1238
1239     i++;
1240   }
1241
1242   //no address with address_index exists, in this case this action should not be callable
1243   GNUNET_assert(GNUNET_NO);
1244 }
1245
1246 /**
1247  * Puts the action into effect by calling the according function
1248  *
1249  * @param solver the solver handle
1250  * @param agent the action handle
1251  * @param action the action to perform by the solver
1252  */
1253 static void
1254 envi_do_action (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int action)
1255 {
1256   int address_index;
1257
1258   switch (action)
1259   {
1260   case RIL_ACTION_NOTHING:
1261     break;
1262   case RIL_ACTION_BW_IN_DBL:
1263     envi_action_bw_double (solver, agent, GNUNET_YES);
1264     break;
1265   case RIL_ACTION_BW_IN_HLV:
1266     envi_action_bw_halven (solver, agent, GNUNET_YES);
1267     break;
1268   case RIL_ACTION_BW_IN_INC:
1269     envi_action_bw_inc (solver, agent, GNUNET_YES);
1270     break;
1271   case RIL_ACTION_BW_IN_DEC:
1272     envi_action_bw_dec (solver, agent, GNUNET_YES);
1273     break;
1274   case RIL_ACTION_BW_OUT_DBL:
1275     envi_action_bw_double (solver, agent, GNUNET_NO);
1276     break;
1277   case RIL_ACTION_BW_OUT_HLV:
1278     envi_action_bw_halven (solver, agent, GNUNET_NO);
1279     break;
1280   case RIL_ACTION_BW_OUT_INC:
1281     envi_action_bw_inc (solver, agent, GNUNET_NO);
1282     break;
1283   case RIL_ACTION_BW_OUT_DEC:
1284     envi_action_bw_dec (solver, agent, GNUNET_NO);
1285     break;
1286   default:
1287     if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action
1288     {
1289       address_index = action - RIL_ACTION_TYPE_NUM;
1290
1291       GNUNET_assert(address_index >= 0);
1292       GNUNET_assert(
1293           address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked));
1294
1295       envi_action_address_switch (solver, agent, address_index);
1296       break;
1297     }
1298     // error - action does not exist
1299     GNUNET_assert(GNUNET_NO);
1300   }
1301 }
1302
1303 /**
1304  * Selects the next action using the e-greedy strategy. I.e. with a probability
1305  * of (1-e) the action with the maximum expected return will be chosen
1306  * (=> exploitation) and with probability (e) a random action will be chosen.
1307  * In case the Q-learning rule is set, the function also resets the eligibility
1308  * traces in the exploration case (after Watkin's Q-learning).
1309  *
1310  * @param agent the agent selecting an action
1311  * @param state the current state-feature vector
1312  * @return the action index
1313  */
1314 static int
1315 agent_select_egreedy (struct RIL_Peer_Agent *agent, double *state)
1316 {
1317   int action;
1318   double r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1319         UINT32_MAX) / (double) UINT32_MAX;
1320
1321   if (r < agent->envi->parameters.epsilon) //explore
1322   {
1323     action = agent_get_action_random(agent);
1324     if (RIL_ALGO_Q == agent->envi->parameters.algorithm)
1325     {
1326       agent->eligibility_reset = GNUNET_YES;
1327     }
1328     agent->envi->parameters.epsilon *= agent->envi->parameters.epsilon_decay;
1329     return action;
1330   }
1331   else //exploit
1332   {
1333     action = agent_get_action_max(agent, state);
1334     return action;
1335   }
1336 }
1337
1338 /**
1339  * Selects the next action with a probability corresponding to its value. The
1340  * probability is calculated using a Boltzmann distribution with a temperature
1341  * value. The higher the temperature, the more are the action selection
1342  * probabilities the same. With a temperature of 0, the selection is greedy,
1343  * i.e. always the action with the highest value is chosen.
1344  * @param agent
1345  * @param state
1346  * @return
1347  */
1348 static int
1349 agent_select_softmax (struct RIL_Peer_Agent *agent, double *state)
1350 {
1351   int i;
1352   int a_max;
1353   double eqt[agent->n];
1354   double p[agent->n];
1355   double sum = 0;
1356   double r;
1357
1358   a_max = agent_get_action_max(agent, state);
1359
1360   for (i=0; i<agent->n; i++)
1361   {
1362     if (agent_action_is_possible(agent, i))
1363     {
1364       eqt[i] = exp(agent_q(agent,state,i) / agent->envi->parameters.temperature);
1365       if (isinf (eqt[i]))
1366         eqt[i] = isinf(eqt[i]) * UINT32_MAX;
1367       sum += eqt[i];
1368     }
1369   }
1370   for (i=0; i<agent->n; i++)
1371   {
1372     if (agent_action_is_possible(agent, i))
1373     {
1374       p[i] = eqt[i]/sum;
1375     }
1376     else
1377     {
1378       p[i] = 0;
1379     }
1380   }
1381   r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1382       UINT32_MAX) / (double) UINT32_MAX;
1383   sum = 0;
1384   for (i=0; i<agent->n; i++)
1385   {
1386     if (sum + p[i] > r)
1387     {
1388       if (i != a_max)
1389       {
1390         if (RIL_ALGO_Q == agent->envi->parameters.algorithm)
1391           agent->eligibility_reset = GNUNET_YES;
1392         agent->envi->parameters.temperature *= agent->envi->parameters.temperature_decay;
1393       }
1394       return i;
1395     }
1396     sum += p[i];
1397   }
1398   GNUNET_assert(GNUNET_NO);
1399   return RIL_ACTION_INVALID;
1400 }
1401
1402 /**
1403  * Select the next action of an agent either according to the e-greedy strategy
1404  * or the softmax strategy.
1405  *
1406  * @param agent the agent in question
1407  * @param state the current state-feature vector
1408  * @return the action index
1409  */
1410 static int
1411 agent_select_action (struct RIL_Peer_Agent *agent, double *state)
1412 {
1413   if (agent->envi->parameters.select == RIL_SELECT_EGREEDY)
1414   {
1415     return agent_select_egreedy(agent, state);
1416   }
1417   else
1418   {
1419     return agent_select_softmax(agent, state);
1420   }
1421 }
1422
1423 /**
1424  * Performs one step of the Markov Decision Process. Other than in the literature the step starts
1425  * after having done the last action a_old. It observes the new state s_next and the reward
1426  * received. Then the coefficient update is done according to the SARSA or Q-learning method. The
1427  * next action is put into effect.
1428  *
1429  * @param agent the agent performing the step
1430  */
1431 static void
1432 agent_step (struct RIL_Peer_Agent *agent)
1433 {
1434   int a_next = RIL_ACTION_INVALID;
1435   int a_max;
1436   double *s_next;
1437   double reward;
1438
1439   LOG(GNUNET_ERROR_TYPE_DEBUG, "    agent_step() Peer '%s', algorithm %s\n",
1440       GNUNET_i2s (&agent->peer),
1441       agent->envi->parameters.algorithm ? "Q" : "SARSA");
1442
1443   s_next = envi_get_state (agent->envi, agent);
1444   reward = envi_get_reward (agent->envi, agent);
1445
1446   if (agent->eligibility_reset)
1447   {
1448     agent_modify_eligibility(agent, RIL_E_ZERO, NULL, -1);
1449     agent->eligibility_reset = GNUNET_NO;
1450   }
1451   else
1452   {
1453     agent_modify_eligibility (agent, RIL_E_DECAY, NULL, -1);
1454   }
1455   if (RIL_ACTION_INVALID != agent->a_old)
1456   {
1457     agent_modify_eligibility (agent, agent->envi->parameters.eligibility_trace_mode, agent->s_old, agent->a_old);
1458   }
1459
1460   switch (agent->envi->parameters.algorithm)
1461   {
1462   case RIL_ALGO_SARSA:
1463     a_next = agent_select_action (agent, s_next);
1464     if (RIL_ACTION_INVALID != agent->a_old)
1465     {
1466       //updates weights with selected action (on-policy), if not first step
1467       agent_update (agent, reward, s_next, a_next);
1468     }
1469     break;
1470
1471   case RIL_ALGO_Q:
1472     a_max = agent_get_action_max (agent, s_next);
1473     if (RIL_ACTION_INVALID != agent->a_old)
1474     {
1475       //updates weights with best action, disregarding actually selected action (off-policy), if not first step
1476       agent_update (agent, reward, s_next, a_max);
1477     }
1478     a_next = agent_select_action (agent, s_next);
1479     break;
1480   }
1481
1482   GNUNET_assert(RIL_ACTION_INVALID != a_next);
1483
1484   LOG (GNUNET_ERROR_TYPE_DEBUG, "step()  Step# %llu  R: %f  IN %llu  OUT %llu  A: %d\n",
1485         agent->step_count,
1486         reward,
1487         agent->bw_in/1024,
1488         agent->bw_out/1024,
1489         a_next);
1490
1491   envi_do_action (agent->envi, agent, a_next);
1492
1493   GNUNET_free(agent->s_old);
1494   agent->s_old = s_next;
1495   agent->a_old = a_next;
1496
1497   agent->step_count += 1;
1498 }
1499
1500 /**
1501  * Prototype of the ril_step() procedure
1502  *
1503  * @param solver the solver handle
1504  */
1505 static void
1506 ril_step (struct GAS_RIL_Handle *solver);
1507
1508
1509 /**
1510  * Task for the scheduler, which performs one step and lets the solver know that
1511  * no further step is scheduled.
1512  *
1513  * @param cls the solver handle
1514  */
1515 static void
1516 ril_step_scheduler_task (void *cls)
1517 {
1518   struct GAS_RIL_Handle *solver = cls;
1519
1520   solver->step_next_task_id = NULL;
1521   ril_step (solver);
1522 }
1523
1524 /**
1525  * Determines how much of the available bandwidth is assigned. If more is
1526  * assigned than available it returns 1. The function is used to determine the
1527  * step size of the adaptive stepping.
1528  *
1529  * @param solver the solver handle
1530  * @return the ratio
1531  */
1532 static double
1533 ril_get_used_resource_ratio (struct GAS_RIL_Handle *solver)
1534 {
1535   int i;
1536   struct RIL_Scope net;
1537   unsigned long long sum_assigned = 0;
1538   unsigned long long sum_available = 0;
1539   double ratio;
1540
1541   for (i = 0; i < solver->networks_count; i++)
1542   {
1543     net = solver->network_entries[i];
1544     if (net.bw_in_assigned > 0) //only consider scopes where an address is actually active
1545     {
1546       sum_assigned += net.bw_in_utilized;
1547       sum_assigned += net.bw_out_utilized;
1548       sum_available += net.bw_in_available;
1549       sum_available += net.bw_out_available;
1550     }
1551   }
1552   if (sum_available > 0)
1553   {
1554     ratio = ((double) sum_assigned) / ((double) sum_available);
1555   }
1556   else
1557   {
1558     ratio = 0;
1559   }
1560
1561   return ratio > 1 ? 1 : ratio; //overutilization is possible, cap at 1
1562 }
1563
1564 /**
1565  * Lookup network struct by type
1566  *
1567  * @param s the solver handle
1568  * @param type the network type
1569  * @return the network struct
1570  */
1571 static struct RIL_Scope *
1572 ril_get_network (struct GAS_RIL_Handle *s, uint32_t type)
1573 {
1574   int i;
1575
1576   for (i = 0; i < s->networks_count; i++)
1577   {
1578     if (s->network_entries[i].type == type)
1579     {
1580       return &s->network_entries[i];
1581     }
1582   }
1583   return NULL ;
1584 }
1585
1586 /**
1587  * Determines whether more connections are allocated in a network scope, than
1588  * they would theoretically fit. This is used as a heuristic to determine,
1589  * whether a new connection can be allocated or not.
1590  *
1591  * @param solver the solver handle
1592  * @param network the network scope in question
1593  * @return GNUNET_YES if there are theoretically enough resources left
1594  */
1595 static int
1596 ril_network_is_not_full (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
1597 {
1598   struct RIL_Scope *net;
1599   struct RIL_Peer_Agent *agent;
1600   unsigned long long address_count = 0;
1601
1602   for (agent = solver->agents_head; NULL != agent; agent = agent->next)
1603   {
1604     if (agent->address_inuse && agent->is_active)
1605     {
1606       net = agent->address_inuse->solver_information;
1607       if (net->type == network)
1608       {
1609         address_count++;
1610       }
1611     }
1612   }
1613
1614   net = ril_get_network (solver, network);
1615   return (net->bw_in_available > RIL_MIN_BW * address_count) && (net->bw_out_available > RIL_MIN_BW * address_count);
1616 }
1617
1618 /**
1619  * Unblocks an agent for which a connection request is there, that could not
1620  * be satisfied. Iterates over the addresses of the agent, if one of its
1621  * addresses can now be allocated in its scope the agent is unblocked,
1622  * otherwise it remains unchanged.
1623  *
1624  * @param solver the solver handle
1625  * @param agent the agent in question
1626  * @param silent
1627  */
1628 static void
1629 ril_try_unblock_agent (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int silent)
1630 {
1631   struct RIL_Address_Wrapped *addr_wrap;
1632   struct RIL_Scope *net;
1633   unsigned long long start_in;
1634   unsigned long long start_out;
1635
1636   for (addr_wrap = agent->addresses_head; NULL != addr_wrap; addr_wrap = addr_wrap->next)
1637   {
1638     net = addr_wrap->address_naked->solver_information;
1639     if (ril_network_is_not_full(solver, net->type))
1640     {
1641       if (NULL == agent->address_inuse)
1642       {
1643         start_in = net->bw_in_available < net->bw_in_utilized ? (net->bw_in_available - net->bw_in_utilized) / 2 : RIL_MIN_BW;
1644         start_out = net->bw_out_available < net->bw_out_utilized ? (net->bw_out_available - net->bw_out_utilized) / 2 : RIL_MIN_BW;
1645         envi_set_active_suggestion (solver, agent, addr_wrap->address_naked, start_in, start_out, silent);
1646       }
1647       return;
1648     }
1649   }
1650   agent->address_inuse = NULL;
1651 }
1652
1653 /**
1654  * Determines how much the reward needs to be discounted depending on the amount
1655  * of time, which has passed since the last time-step.
1656  *
1657  * @param solver the solver handle
1658  */
1659 static void
1660 ril_calculate_discount (struct GAS_RIL_Handle *solver)
1661 {
1662   struct GNUNET_TIME_Absolute time_now;
1663   struct GNUNET_TIME_Relative time_delta;
1664   double tau;
1665
1666   // MDP case only for debugging purposes
1667   if (solver->simulate)
1668   {
1669     solver->global_discount_variable = solver->parameters.gamma;
1670     solver->global_discount_integrated = 1;
1671     return;
1672   }
1673
1674   // semi-MDP case
1675
1676   //calculate tau, i.e. how many real valued time units have passed, one time unit is one minimum time step
1677   time_now = GNUNET_TIME_absolute_get ();
1678   time_delta = GNUNET_TIME_absolute_get_difference (solver->step_time_last, time_now);
1679   solver->step_time_last = time_now;
1680   tau = (double) time_delta.rel_value_us
1681       / (double) solver->parameters.step_time_min.rel_value_us;
1682
1683   //calculate reward discounts (once per step for all agents)
1684   solver->global_discount_variable = pow (M_E, ((-1.0) * ((double) solver->parameters.beta) * tau));
1685   solver->global_discount_integrated = (1.0 - solver->global_discount_variable)
1686       / (double) solver->parameters.beta;
1687 }
1688
1689 /**
1690  * Count the number of active agents/connections in a network scope
1691  *
1692  * @param solver the solver handle
1693  * @param scope the network scope in question
1694  * @return the number of allocated connections
1695  */
1696 static int
1697 ril_network_count_active_agents (struct GAS_RIL_Handle *solver, struct RIL_Scope *scope)
1698 {
1699   int c = 0;
1700   struct RIL_Peer_Agent *cur_agent;
1701
1702   for (cur_agent = solver->agents_head; NULL != cur_agent; cur_agent = cur_agent->next)
1703   {
1704     if (cur_agent->is_active && cur_agent->address_inuse && (cur_agent->address_inuse->solver_information == scope))
1705     {
1706       c++;
1707     }
1708   }
1709   return c;
1710 }
1711
1712 /**
1713  * Calculates how much bandwidth is assigned in sum in a network scope, either
1714  * in the inbound or in the outbound direction.
1715  *
1716  * @param solver the solver handle
1717  * @param type the type of the network scope in question
1718  * @param direction_in GNUNET_YES if the inbound direction should be summed up,
1719  *   otherwise the outbound direction will be summed up
1720  * @return the sum of the assigned bandwidths
1721  */
1722 static unsigned long long
1723 ril_network_get_assigned (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type type, int direction_in)
1724 {
1725   struct RIL_Peer_Agent *cur;
1726   struct RIL_Scope *net;
1727   unsigned long long sum = 0;
1728
1729   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1730   {
1731     if (cur->is_active && cur->address_inuse)
1732     {
1733       net = cur->address_inuse->solver_information;
1734       if (net->type == type)
1735       {
1736         if (direction_in)
1737           sum += cur->bw_in;
1738         else
1739           sum += cur->bw_out;
1740       }
1741     }
1742   }
1743
1744   return sum;
1745 }
1746
1747 /**
1748  * Calculates how much bandwidth is actually utilized in sum in a network scope,
1749  * either in the inbound or in the outbound direction.
1750  *
1751  * @param solver the solver handle
1752  * @param type the type of the network scope in question
1753  * @param direction_in GNUNET_YES if the inbound direction should be summed up,
1754  *   otherwise the outbound direction will be summed up
1755  * @return the sum of the utilized bandwidths (in bytes/second)
1756  */
1757 static unsigned long long
1758 ril_network_get_utilized (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type type, int direction_in)
1759 {
1760   struct RIL_Peer_Agent *cur;
1761   struct RIL_Scope *net;
1762   unsigned long long sum = 0;
1763
1764   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1765   {
1766     if (cur->is_active && cur->address_inuse)
1767     {
1768       net = cur->address_inuse->solver_information;
1769       if (net->type == type)
1770       {
1771         if (direction_in)
1772           sum += cur->address_inuse->norm_utilization_in.norm;
1773         else
1774           sum += cur->address_inuse->norm_utilization_out.norm;
1775       }
1776     }
1777   }
1778
1779   return sum;
1780 }
1781
1782 /**
1783  * Retrieves the state of the network scope, so that its attributes are up-to-
1784  * date.
1785  *
1786  * @param solver the solver handle
1787  */
1788 static void
1789 ril_networks_update_state (struct GAS_RIL_Handle *solver)
1790 {
1791   int c;
1792   struct RIL_Scope *net;
1793
1794   for (c = 0; c < solver->networks_count; c++)
1795   {
1796     net = &solver->network_entries[c];
1797     net->bw_in_assigned = ril_network_get_assigned(solver, net->type, GNUNET_YES);
1798     net->bw_in_utilized = ril_network_get_utilized(solver, net->type, GNUNET_YES);
1799     net->bw_out_assigned = ril_network_get_assigned(solver, net->type, GNUNET_NO);
1800     net->bw_out_utilized = ril_network_get_utilized(solver, net->type, GNUNET_NO);
1801     net->active_agent_count = ril_network_count_active_agents(solver, net);
1802     net->social_welfare = ril_network_get_social_welfare(solver, net);
1803   }
1804 }
1805
1806 /**
1807  * Schedules the next global step in an adaptive way. The more resources are
1808  * left, the earlier the next step is scheduled. This serves the reactivity of
1809  * the solver to changed inputs.
1810  *
1811  * @param solver the solver handle
1812  */
1813 static void
1814 ril_step_schedule_next (struct GAS_RIL_Handle *solver)
1815 {
1816   double used_ratio;
1817   double factor;
1818   double y;
1819   double offset;
1820   struct GNUNET_TIME_Relative time_next;
1821
1822   used_ratio = ril_get_used_resource_ratio (solver);
1823
1824   GNUNET_assert(
1825       solver->parameters.step_time_min.rel_value_us
1826           <= solver->parameters.step_time_max.rel_value_us);
1827
1828   factor = (double) GNUNET_TIME_relative_subtract (solver->parameters.step_time_max,
1829       solver->parameters.step_time_min).rel_value_us;
1830   offset = (double) solver->parameters.step_time_min.rel_value_us;
1831   y = factor * pow (used_ratio, RIL_INTERVAL_EXPONENT) + offset;
1832
1833   GNUNET_assert(y <= (double) solver->parameters.step_time_max.rel_value_us);
1834   GNUNET_assert(y >= (double) solver->parameters.step_time_min.rel_value_us);
1835
1836   time_next = GNUNET_TIME_relative_saturating_multiply (GNUNET_TIME_UNIT_MICROSECONDS, (unsigned long long) y);
1837
1838 //  LOG (GNUNET_ERROR_TYPE_INFO, "ratio: %f, factor: %f, offset: %f, y: %f\n",
1839 //      used_ratio,
1840 //      factor,
1841 //      offset,
1842 //      y);
1843
1844   if (solver->simulate)
1845   {
1846     time_next = GNUNET_TIME_UNIT_ZERO;
1847   }
1848
1849   if ((NULL == solver->step_next_task_id) && (GNUNET_NO == solver->done))
1850   {
1851     solver->step_next_task_id = GNUNET_SCHEDULER_add_delayed (time_next, &ril_step_scheduler_task,
1852           solver);
1853   }
1854 }
1855
1856 /**
1857  * Triggers one step per agent
1858  *
1859  * @param solver
1860  */
1861 static void
1862 ril_step (struct GAS_RIL_Handle *solver)
1863 {
1864   struct RIL_Peer_Agent *cur;
1865
1866   if (GNUNET_YES == solver->bulk_lock)
1867   {
1868     solver->bulk_changes++;
1869     return;
1870   }
1871
1872   ril_inform (solver, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS);
1873
1874   LOG(GNUNET_ERROR_TYPE_DEBUG, "    RIL step number %d\n", solver->step_count);
1875
1876   if (0 == solver->step_count)
1877   {
1878     solver->step_time_last = GNUNET_TIME_absolute_get ();
1879   }
1880
1881   ril_calculate_discount (solver);
1882   ril_networks_update_state (solver);
1883
1884   //trigger one step per active, unblocked agent
1885   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1886   {
1887     if (cur->is_active)
1888     {
1889       if (NULL == cur->address_inuse)
1890       {
1891         ril_try_unblock_agent(solver, cur, GNUNET_NO);
1892       }
1893       if (cur->address_inuse)
1894       {
1895         agent_step (cur);
1896       }
1897     }
1898   }
1899
1900   ril_networks_update_state (solver);
1901
1902   solver->step_count++;
1903   ril_step_schedule_next (solver);
1904
1905   ril_inform (solver, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS);
1906
1907   ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, GAS_STAT_SUCCESS);
1908   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1909   {
1910     if (cur->suggestion_issue) {
1911       solver->env->bandwidth_changed_cb (solver->env->cls,
1912                                          cur->suggestion_address);
1913       cur->suggestion_issue = GNUNET_NO;
1914     }
1915   }
1916   ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, GAS_STAT_SUCCESS);
1917 }
1918
1919 /**
1920  * Initializes the matrix W of parameter vectors theta with small random numbers.
1921  *
1922  * @param agent The respective agent
1923  */
1924 static void
1925 agent_w_init (struct RIL_Peer_Agent *agent)
1926 {
1927   int i;
1928   int k;
1929
1930   for (i = 0; i < agent->n; i++)
1931   {
1932     for (k = 0; k < agent->m; k++)
1933     {
1934       agent->W[i][k] = agent->envi->parameters.alpha * (1.0 - 2.0 * ((double) GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX)/(double) UINT32_MAX));
1935     }
1936   }
1937 }
1938
1939 /**
1940  * Initialize an agent without addresses and its knowledge base
1941  *
1942  * @param s ril solver
1943  * @param peer the one in question
1944  * @return handle to the new agent
1945  */
1946 static struct RIL_Peer_Agent *
1947 agent_init (void *s, const struct GNUNET_PeerIdentity *peer)
1948 {
1949   int i;
1950   struct GAS_RIL_Handle * solver = s;
1951   struct RIL_Peer_Agent * agent = GNUNET_new (struct RIL_Peer_Agent);
1952
1953   agent->envi = solver;
1954   agent->peer = *peer;
1955   agent->step_count = 0;
1956   agent->is_active = GNUNET_NO;
1957   agent->bw_in = RIL_MIN_BW;
1958   agent->bw_out = RIL_MIN_BW;
1959   agent->suggestion_issue = GNUNET_NO;
1960   agent->n = RIL_ACTION_TYPE_NUM;
1961   agent->m = 0;
1962   agent->W = (double **) GNUNET_malloc (sizeof (double *) * agent->n);
1963   agent->E = (double **) GNUNET_malloc (sizeof (double *) * agent->n);
1964   for (i = 0; i < agent->n; i++)
1965   {
1966     agent->W[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1967     agent->E[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1968   }
1969   agent_w_init(agent);
1970   agent->eligibility_reset = GNUNET_NO;
1971   agent->a_old = RIL_ACTION_INVALID;
1972   agent->s_old = GNUNET_malloc (sizeof (double) * agent->m);
1973   agent->address_inuse = NULL;
1974   agent->objective_old = 0;
1975   agent->nop_bonus = 0;
1976
1977   return agent;
1978 }
1979
1980 /**
1981  * Deallocate agent
1982  *
1983  * @param solver the solver handle
1984  * @param agent the agent to retire
1985  */
1986 static void
1987 agent_die (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
1988 {
1989   int i;
1990
1991   for (i = 0; i < agent->n; i++)
1992   {
1993     GNUNET_free_non_null(agent->W[i]);
1994     GNUNET_free_non_null(agent->E[i]);
1995   }
1996   GNUNET_free_non_null(agent->W);
1997   GNUNET_free_non_null(agent->E);
1998   GNUNET_free_non_null(agent->s_old);
1999   GNUNET_free(agent);
2000 }
2001
2002 /**
2003  * Returns the agent for a peer
2004  *
2005  * @param solver the solver handle
2006  * @param peer the identity of the peer
2007  * @param create whether or not to create an agent, if none is allocated yet
2008  * @return the agent
2009  */
2010 static struct RIL_Peer_Agent *
2011 ril_get_agent (struct GAS_RIL_Handle *solver, const struct GNUNET_PeerIdentity *peer, int create)
2012 {
2013   struct RIL_Peer_Agent *cur;
2014
2015   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
2016   {
2017     if (0 == memcmp (peer, &cur->peer, sizeof(struct GNUNET_PeerIdentity)))
2018     {
2019       return cur;
2020     }
2021   }
2022
2023   if (create)
2024   {
2025     cur = agent_init (solver, peer);
2026     GNUNET_CONTAINER_DLL_insert_tail(solver->agents_head, solver->agents_tail, cur);
2027     return cur;
2028   }
2029   return NULL ;
2030 }
2031
2032 /**
2033  * Determine whether at least the minimum bandwidth is set for the network. Otherwise the network is
2034  * considered inactive and not used. Addresses in an inactive network are ignored.
2035  *
2036  * @param solver solver handle
2037  * @param network the network type
2038  * @return whether or not the network is considered active
2039  */
2040 static int
2041 ril_network_is_active (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
2042 {
2043   struct RIL_Scope *net;
2044
2045   net = ril_get_network (solver, network);
2046   return net->bw_out_available >= RIL_MIN_BW;
2047 }
2048
2049 /**
2050  * Cuts a slice out of a vector of elements. This is used to decrease the size of the matrix storing
2051  * the reward function approximation. It copies the memory, which is not cut, to the new vector,
2052  * frees the memory of the old vector, and redirects the pointer to the new one.
2053  *
2054  * @param old pointer to the pointer to the first element of the vector
2055  * @param element_size byte size of the vector elements
2056  * @param hole_start the first element to cut out
2057  * @param hole_length the number of elements to cut out
2058  * @param old_length the length of the old vector
2059  */
2060 static void
2061 ril_cut_from_vector (void **old,
2062     size_t element_size,
2063     unsigned int hole_start,
2064     unsigned int hole_length,
2065     unsigned int old_length)
2066 {
2067   char *tmpptr;
2068   char *oldptr = (char *) *old;
2069   size_t size;
2070   unsigned int bytes_before;
2071   unsigned int bytes_hole;
2072   unsigned int bytes_after;
2073
2074   GNUNET_assert(old_length >= hole_length);
2075   GNUNET_assert(old_length >= (hole_start + hole_length));
2076
2077   size = element_size * (old_length - hole_length);
2078
2079   bytes_before = element_size * hole_start;
2080   bytes_hole = element_size * hole_length;
2081   bytes_after = element_size * (old_length - hole_start - hole_length);
2082
2083   if (0 == size)
2084   {
2085     tmpptr = NULL;
2086   }
2087   else
2088   {
2089     tmpptr = GNUNET_malloc (size);
2090     GNUNET_memcpy (tmpptr, oldptr, bytes_before);
2091     GNUNET_memcpy (tmpptr + bytes_before, oldptr + (bytes_before + bytes_hole), bytes_after);
2092   }
2093   if (NULL != *old)
2094   {
2095     GNUNET_free(*old);
2096   }
2097   *old = (void *) tmpptr;
2098 }
2099
2100 /*
2101  *  Solver API functions
2102  *  ---------------------------
2103  */
2104
2105 /**
2106  * Change relative preference for quality in solver
2107  *
2108  * @param solver the solver handle
2109  * @param peer the peer to change the preference for
2110  * @param kind the kind to change the preference
2111  * @param pref_rel the normalized preference value for this kind over all clients
2112  */
2113 static void
2114 GAS_ril_address_change_preference (void *solver,
2115                                    const struct GNUNET_PeerIdentity *peer,
2116                                    enum GNUNET_ATS_PreferenceKind kind,
2117                                    double pref_rel)
2118 {
2119   LOG(GNUNET_ERROR_TYPE_DEBUG,
2120       "API_address_change_preference() Preference '%s' for peer '%s' changed to %.2f \n",
2121       GNUNET_ATS_print_preference_type (kind), GNUNET_i2s (peer), pref_rel);
2122
2123   struct GAS_RIL_Handle *s = solver;
2124
2125   s->parameters.temperature = s->parameters.temperature_init;
2126   s->parameters.epsilon = s->parameters.epsilon_init;
2127   ril_step (s);
2128 }
2129
2130
2131 /**
2132  * Add a new address for a peer to the solver
2133  *
2134  * The address is already contained in the addresses hashmap!
2135  *
2136  * @param solver the solver Handle
2137  * @param address the address to add
2138  * @param network network type of this address
2139  */
2140 static void
2141 GAS_ril_address_add (void *solver,
2142                      struct ATS_Address *address,
2143                      uint32_t network)
2144 {
2145   struct GAS_RIL_Handle *s = solver;
2146   struct RIL_Peer_Agent *agent;
2147   struct RIL_Address_Wrapped *address_wrapped;
2148   struct RIL_Scope *net;
2149   unsigned int m_new;
2150   unsigned int m_old;
2151   unsigned int n_new;
2152   unsigned int n_old;
2153   int i;
2154   unsigned int zero;
2155
2156   LOG (GNUNET_ERROR_TYPE_DEBUG,
2157        "API_address_add()\n");
2158
2159   net = ril_get_network (s, network);
2160   address->solver_information = net;
2161
2162   if (!ril_network_is_active (s, network))
2163   {
2164     LOG(GNUNET_ERROR_TYPE_DEBUG,
2165         "API_address_add() Did not add %s address %s for peer '%s', network does not have enough bandwidth\n",
2166         address->plugin, address->addr, GNUNET_i2s (&address->peer));
2167     return;
2168   }
2169
2170   s->parameters.temperature = s->parameters.temperature_init;
2171   s->parameters.epsilon = s->parameters.epsilon_init;
2172
2173   agent = ril_get_agent (s, &address->peer, GNUNET_YES);
2174
2175   //add address
2176   address_wrapped = GNUNET_new (struct RIL_Address_Wrapped);
2177   address_wrapped->address_naked = address;
2178   GNUNET_CONTAINER_DLL_insert_tail(agent->addresses_head, agent->addresses_tail, address_wrapped);
2179
2180   //increase size of W
2181   m_new = agent->m + ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1));
2182   m_old = agent->m;
2183   n_new = agent->n + 1;
2184   n_old = agent->n;
2185
2186   GNUNET_array_grow(agent->W, agent->n, n_new);
2187   agent->n = n_old;
2188   GNUNET_array_grow(agent->E, agent->n, n_new);
2189   for (i = 0; i < n_new; i++)
2190   {
2191     if (i < n_old)
2192     {
2193       agent->m = m_old;
2194       GNUNET_array_grow(agent->W[i], agent->m, m_new);
2195       agent->m = m_old;
2196       GNUNET_array_grow(agent->E[i], agent->m, m_new);
2197     }
2198     else
2199     {
2200       zero = 0;
2201       GNUNET_array_grow(agent->W[i], zero, m_new);
2202       zero = 0;
2203       GNUNET_array_grow(agent->E[i], zero, m_new);
2204     }
2205   }
2206
2207   //increase size of old state vector
2208   agent->m = m_old;
2209   GNUNET_array_grow(agent->s_old, agent->m, m_new);
2210
2211   ril_try_unblock_agent(s, agent, GNUNET_NO);
2212
2213   ril_step (s);
2214
2215   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_add() Added %s %s address %s for peer '%s'\n",
2216       address->active ? "active" : "inactive", address->plugin, address->addr,
2217       GNUNET_i2s (&address->peer));
2218 }
2219
2220 /**
2221  * Delete an address in the solver
2222  *
2223  * The address is not contained in the address hashmap anymore!
2224  *
2225  * @param solver the solver handle
2226  * @param address the address to remove
2227  */
2228 static void
2229 GAS_ril_address_delete (void *solver,
2230                         struct ATS_Address *address)
2231 {
2232   struct GAS_RIL_Handle *s = solver;
2233   struct RIL_Peer_Agent *agent;
2234   struct RIL_Address_Wrapped *address_wrapped;
2235   int address_index;
2236   unsigned int m_new;
2237   unsigned int n_new;
2238   int i;
2239   struct RIL_Scope *net;
2240
2241   LOG (GNUNET_ERROR_TYPE_DEBUG,
2242        "API_address_delete() Delete %s %s address %s for peer '%s'\n",
2243        address->active ? "active" : "inactive",
2244        address->plugin,
2245        address->addr,
2246        GNUNET_i2s (&address->peer));
2247
2248   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
2249   if (NULL == agent)
2250   {
2251     net = address->solver_information;
2252     GNUNET_assert(! ril_network_is_active (s, net->type));
2253     LOG (GNUNET_ERROR_TYPE_DEBUG,
2254          "No agent allocated for peer yet, since address was in inactive network\n");
2255     return;
2256   }
2257
2258   s->parameters.temperature = s->parameters.temperature_init;
2259   s->parameters.epsilon = s->parameters.epsilon_init;
2260
2261   address_index = agent_address_get_index (agent, address);
2262   address_wrapped = agent_address_get_wrapped (agent, address);
2263
2264   if (NULL == address_wrapped)
2265   {
2266     net = address->solver_information;
2267     LOG (GNUNET_ERROR_TYPE_DEBUG,
2268          "Address not considered by agent, address was in inactive network\n");
2269     return;
2270   }
2271   GNUNET_CONTAINER_DLL_remove (agent->addresses_head,
2272                                agent->addresses_tail,
2273                                address_wrapped);
2274   GNUNET_free (address_wrapped);
2275
2276   //decrease W
2277   m_new = agent->m - ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1));
2278   n_new = agent->n - 1;
2279
2280   for (i = 0; i < agent->n; i++)
2281   {
2282     ril_cut_from_vector ((void **) &agent->W[i], sizeof(double),
2283         address_index * ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)),
2284         ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), agent->m);
2285     ril_cut_from_vector ((void **) &agent->E[i], sizeof(double),
2286         address_index * ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)),
2287         ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), agent->m);
2288   }
2289   GNUNET_free_non_null(agent->W[RIL_ACTION_TYPE_NUM + address_index]);
2290   GNUNET_free_non_null(agent->E[RIL_ACTION_TYPE_NUM + address_index]);
2291   ril_cut_from_vector ((void **) &agent->W, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index,
2292       1, agent->n);
2293   ril_cut_from_vector ((void **) &agent->E, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index,
2294       1, agent->n);
2295   //correct last action
2296   if (agent->a_old > (RIL_ACTION_TYPE_NUM + address_index))
2297   {
2298     agent->a_old -= 1;
2299   }
2300   else if (agent->a_old == (RIL_ACTION_TYPE_NUM + address_index))
2301   {
2302     agent->a_old = RIL_ACTION_INVALID;
2303   }
2304   //decrease old state vector
2305   ril_cut_from_vector ((void **) &agent->s_old, sizeof(double),
2306                        address_index * ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)),
2307                        ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), agent->m);
2308   agent->m = m_new;
2309   agent->n = n_new;
2310
2311   if (agent->address_inuse == address)
2312   {
2313     if (NULL != agent->addresses_head) //if peer has an address left, use it
2314     {
2315       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2316                   "Active address died, suggesting alternative!\n");
2317       envi_set_active_suggestion (s,
2318                                   agent,
2319                                   agent->addresses_head->address_naked,
2320                                   agent->bw_in,
2321                                   agent->bw_out,
2322                                   GNUNET_YES);
2323     }
2324     else
2325     {
2326       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2327                   "Active address died, suggesting disconnect!\n");
2328       envi_set_active_suggestion (s, agent, NULL, 0, 0, GNUNET_NO);
2329     }
2330   }
2331   ril_step (solver);
2332   if (agent->suggestion_address == address)
2333   {
2334     agent->suggestion_issue = GNUNET_NO;
2335     agent->suggestion_address = NULL;
2336   }
2337   GNUNET_assert (agent->address_inuse != address);
2338 }
2339
2340
2341 /**
2342  * Update the properties of an address in the solver
2343  *
2344  * @param solver solver handle
2345  * @param address the address
2346  */
2347 static void
2348 GAS_ril_address_property_changed (void *solver,
2349                                   struct ATS_Address *address)
2350 {
2351   struct GAS_RIL_Handle *s = solver;
2352
2353   LOG(GNUNET_ERROR_TYPE_DEBUG,
2354       "Properties for peer '%s' address changed\n",
2355       GNUNET_i2s (&address->peer));
2356   s->parameters.temperature = s->parameters.temperature_init;
2357   s->parameters.epsilon = s->parameters.epsilon_init;
2358   ril_step (s);
2359 }
2360
2361
2362 /**
2363  * Give feedback about the current assignment
2364  *
2365  * @param solver the solver handle
2366  * @param application the application
2367  * @param peer the peer to change the preference for
2368  * @param scope the time interval for this feedback: [now - scope .. now]
2369  * @param kind the kind to change the preference
2370  * @param score the score
2371  */
2372 static void
2373 GAS_ril_address_preference_feedback (void *solver,
2374                                      struct GNUNET_SERVICE_Client *application,
2375                                      const struct GNUNET_PeerIdentity *peer,
2376                                      const struct GNUNET_TIME_Relative scope,
2377                                      enum GNUNET_ATS_PreferenceKind kind,
2378                                      double score)
2379 {
2380   LOG (GNUNET_ERROR_TYPE_DEBUG,
2381        "API_address_preference_feedback() Peer '%s' got a feedback of %+.3f from application %s for "
2382        "preference %s for %d seconds\n",
2383        GNUNET_i2s (peer),
2384        "UNKNOWN",
2385        GNUNET_ATS_print_preference_type (kind),
2386        scope.rel_value_us / 1000000);
2387 }
2388
2389
2390 /**
2391  * Start a bulk operation
2392  *
2393  * @param solver the solver
2394  */
2395 static void
2396 GAS_ril_bulk_start (void *solver)
2397 {
2398   struct GAS_RIL_Handle *s = solver;
2399
2400   LOG (GNUNET_ERROR_TYPE_DEBUG,
2401        "API_bulk_start() lock: %d\n", s->bulk_lock+1);
2402
2403   s->bulk_lock++;
2404 }
2405
2406
2407 /**
2408  * Bulk operation done
2409  *
2410  * @param solver the solver handle
2411  */
2412 static void
2413 GAS_ril_bulk_stop (void *solver)
2414 {
2415   struct GAS_RIL_Handle *s = solver;
2416
2417   LOG(GNUNET_ERROR_TYPE_DEBUG,
2418       "API_bulk_stop() lock: %d\n",
2419       s->bulk_lock - 1);
2420
2421   if (s->bulk_lock < 1)
2422   {
2423     GNUNET_break(0);
2424     return;
2425   }
2426   s->bulk_lock--;
2427
2428   if (0 < s->bulk_changes)
2429   {
2430     ril_step (solver);
2431     s->bulk_changes = 0;
2432   }
2433 }
2434
2435
2436 /**
2437  * Tell solver to notify ATS if the address to use changes for a specific
2438  * peer using the bandwidth changed callback
2439  *
2440  * The solver must only notify about changes for peers with pending address
2441  * requests!
2442  *
2443  * @param solver the solver handle
2444  * @param peer the identity of the peer
2445  */
2446 static void
2447 GAS_ril_get_preferred_address (void *solver,
2448                                const struct GNUNET_PeerIdentity *peer)
2449 {
2450   struct GAS_RIL_Handle *s = solver;
2451   struct RIL_Peer_Agent *agent;
2452
2453   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_get_preferred_address()\n");
2454
2455   agent = ril_get_agent (s, peer, GNUNET_YES);
2456
2457   agent->is_active = GNUNET_YES;
2458   envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, agent->bw_out, GNUNET_YES);
2459
2460   ril_try_unblock_agent(solver, agent, GNUNET_YES);
2461
2462   if (agent->address_inuse)
2463   {
2464     LOG(GNUNET_ERROR_TYPE_DEBUG,
2465         "API_get_preferred_address() Activated agent for peer '%s' with %s address %s\n",
2466         GNUNET_i2s (peer), agent->address_inuse->plugin, agent->address_inuse->addr);
2467   }
2468   else
2469   {
2470     LOG(GNUNET_ERROR_TYPE_DEBUG,
2471         "API_get_preferred_address() Activated agent for peer '%s', but no address available\n",
2472         GNUNET_i2s (peer));
2473     s->parameters.temperature = s->parameters.temperature_init;
2474     s->parameters.epsilon = s->parameters.epsilon_init;
2475   }
2476   if (NULL != agent->address_inuse)
2477     s->env->bandwidth_changed_cb (s->env->cls,
2478                                   agent->address_inuse);
2479 }
2480
2481
2482 /**
2483  * Tell solver stop notifying ATS about changes for this peers
2484  *
2485  * The solver must only notify about changes for peers with pending address
2486  * requests!
2487  *
2488  * @param solver the solver handle
2489  * @param peer the peer
2490  */
2491 static void
2492 GAS_ril_stop_get_preferred_address (void *solver,
2493                                     const struct GNUNET_PeerIdentity *peer)
2494 {
2495   struct GAS_RIL_Handle *s = solver;
2496   struct RIL_Peer_Agent *agent;
2497
2498   LOG (GNUNET_ERROR_TYPE_DEBUG,
2499        "API_stop_get_preferred_address()");
2500
2501   agent = ril_get_agent (s, peer, GNUNET_NO);
2502
2503   if (NULL == agent)
2504   {
2505     GNUNET_break(0);
2506     return;
2507   }
2508   if (GNUNET_NO == agent->is_active)
2509   {
2510     GNUNET_break(0);
2511     return;
2512   }
2513
2514   s->parameters.temperature = s->parameters.temperature_init;
2515   s->parameters.epsilon = s->parameters.epsilon_init;
2516
2517   agent->is_active = GNUNET_NO;
2518
2519   envi_set_active_suggestion (s, agent, agent->address_inuse, agent->bw_in, agent->bw_out,
2520       GNUNET_YES);
2521
2522   ril_step (s);
2523
2524   LOG(GNUNET_ERROR_TYPE_DEBUG,
2525       "API_stop_get_preferred_address() Paused agent for peer '%s'\n",
2526       GNUNET_i2s (peer));
2527 }
2528
2529
2530 /**
2531  * Entry point for the plugin
2532  *
2533  * @param cls pointer to the 'struct GNUNET_ATS_PluginEnvironment'
2534  */
2535 void *
2536 libgnunet_plugin_ats_ril_init (void *cls)
2537 {
2538   static struct GNUNET_ATS_SolverFunctions sf;
2539   struct GNUNET_ATS_PluginEnvironment *env = cls;
2540   struct GAS_RIL_Handle *solver = GNUNET_new (struct GAS_RIL_Handle);
2541   struct RIL_Scope * cur;
2542   int c;
2543   char *string;
2544   float f_tmp;
2545
2546   LOG (GNUNET_ERROR_TYPE_DEBUG,
2547        "API_init() Initializing RIL solver\n");
2548
2549   GNUNET_assert (NULL != env);
2550   GNUNET_assert (NULL != env->cfg);
2551   GNUNET_assert (NULL != env->stats);
2552   GNUNET_assert (NULL != env->bandwidth_changed_cb);
2553   GNUNET_assert (NULL != env->get_preferences);
2554
2555   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(env->cfg, "ats", "RIL_RBF_DIVISOR", &solver->parameters.rbf_divisor))
2556   {
2557     solver->parameters.rbf_divisor = RIL_DEFAULT_RBF_DIVISOR;
2558   }
2559
2560   if (GNUNET_OK
2561       != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MIN",
2562           &solver->parameters.step_time_min))
2563   {
2564     solver->parameters.step_time_min = RIL_DEFAULT_STEP_TIME_MIN;
2565   }
2566
2567   if (GNUNET_OK
2568       != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MAX",
2569           &solver->parameters.step_time_max))
2570   {
2571     solver->parameters.step_time_max = RIL_DEFAULT_STEP_TIME_MAX;
2572   }
2573
2574   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_ALGORITHM", &string))
2575   {
2576     GNUNET_STRINGS_utf8_toupper (string, string);
2577     if (0 == strcmp (string, "SARSA"))
2578     {
2579         solver->parameters.algorithm = RIL_ALGO_SARSA;
2580     }
2581     if (0 == strcmp (string, "Q-LEARNING"))
2582     {
2583         solver->parameters.algorithm = RIL_ALGO_Q;
2584     }
2585
2586     GNUNET_free (string);
2587   }
2588   else
2589   {
2590     solver->parameters.algorithm = RIL_DEFAULT_ALGORITHM;
2591   }
2592
2593   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_SELECT", &string))
2594   {
2595     solver->parameters.select = !strcmp (string, "EGREEDY") ? RIL_SELECT_EGREEDY : RIL_SELECT_SOFTMAX;
2596     GNUNET_free (string);
2597   }
2598   else
2599   {
2600     solver->parameters.select = RIL_DEFAULT_SELECT;
2601   }
2602
2603
2604   solver->parameters.beta = RIL_DEFAULT_DISCOUNT_BETA;
2605   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2606       "RIL_DISCOUNT_BETA", &f_tmp))
2607   {
2608     if (f_tmp < 0.0)
2609     {
2610       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2611           "RIL_DISCOUNT_BETA", f_tmp);
2612     }
2613     else
2614     {
2615       solver->parameters.beta = f_tmp;
2616       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
2617           "RIL_DISCOUNT_BETA", f_tmp);
2618     }
2619   }
2620
2621   solver->parameters.gamma = RIL_DEFAULT_DISCOUNT_GAMMA;
2622   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2623       "RIL_DISCOUNT_GAMMA", &f_tmp))
2624   {
2625     if ((f_tmp < 0.0) || (f_tmp > 1.0))
2626     {
2627       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2628           "RIL_DISCOUNT_GAMMA", f_tmp);
2629     }
2630     else
2631     {
2632       solver->parameters.gamma = f_tmp;
2633       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
2634           "RIL_DISCOUNT_GAMMA", f_tmp);
2635     }
2636   }
2637
2638   solver->parameters.alpha = RIL_DEFAULT_GRADIENT_STEP_SIZE;
2639   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2640       "RIL_GRADIENT_STEP_SIZE", &f_tmp))
2641   {
2642     if ((f_tmp < 0.0) || (f_tmp > 1.0))
2643     {
2644       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2645           "RIL_GRADIENT_STEP_SIZE", f_tmp);
2646     }
2647     else
2648     {
2649       solver->parameters.alpha = f_tmp;
2650       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
2651           "RIL_GRADIENT_STEP_SIZE", f_tmp);
2652     }
2653   }
2654
2655   solver->parameters.lambda = RIL_DEFAULT_TRACE_DECAY;
2656   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2657       "RIL_TRACE_DECAY", &f_tmp))
2658   {
2659     if ((f_tmp < 0.0) || (f_tmp > 1.0))
2660     {
2661       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2662           "RIL_TRACE_DECAY", f_tmp);
2663     }
2664     else
2665     {
2666       solver->parameters.lambda = f_tmp;
2667       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
2668           "RIL_TRACE_DECAY", f_tmp);
2669     }
2670   }
2671
2672   solver->parameters.epsilon_init = RIL_DEFAULT_EXPLORE_RATIO;
2673   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2674       "RIL_EXPLORE_RATIO", &f_tmp))
2675   {
2676     if ((f_tmp < 0.0) || (f_tmp > 1.0))
2677     {
2678       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2679           "RIL_EXPLORE_RATIO", f_tmp);
2680     }
2681     else
2682     {
2683       solver->parameters.epsilon_init = f_tmp;
2684       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
2685           "RIL_EXPLORE_RATIO", f_tmp);
2686     }
2687   }
2688
2689   solver->parameters.epsilon_decay = RIL_DEFAULT_EXPLORE_DECAY;
2690   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2691       "RIL_EXPLORE_DECAY", &f_tmp))
2692   {
2693     if ((f_tmp < 0.0) || (f_tmp > 1.0))
2694     {
2695       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2696           "RIL_EXPLORE_DECAY", f_tmp);
2697     }
2698     else
2699     {
2700       solver->parameters.epsilon_decay = f_tmp;
2701       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
2702           "RIL_EXPLORE_DECAY", f_tmp);
2703     }
2704   }
2705
2706   solver->parameters.temperature_init = RIL_DEFAULT_TEMPERATURE;
2707   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2708       "RIL_TEMPERATURE", &f_tmp))
2709   {
2710     if (f_tmp <= 0.0)
2711     {
2712       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2713           "RIL_TEMPERATURE", f_tmp);
2714     }
2715     else
2716     {
2717       solver->parameters.temperature_init = f_tmp;
2718       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
2719           "RIL_TEMPERATURE", f_tmp);
2720     }
2721   }
2722
2723   solver->parameters.temperature_decay = RIL_DEFAULT_TEMPERATURE_DECAY;
2724   if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
2725       "RIL_TEMPERATURE_DECAY", &f_tmp))
2726   {
2727     if ((f_tmp <= 0.0) || solver->parameters.temperature_decay > 1)
2728     {
2729       LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
2730           "RIL_TEMPERATURE_DECAY", f_tmp);
2731     }
2732     else
2733     {
2734       solver->parameters.temperature_decay = f_tmp;
2735       LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
2736           "RIL_TEMPERATURE_DECAY", f_tmp);
2737     }
2738   }
2739
2740   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "ats", "RIL_SIMULATE", &solver->simulate))
2741   {
2742     solver->simulate = GNUNET_NO;
2743   }
2744
2745   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(env->cfg, "ats", "RIL_REPLACE_TRACES"))
2746   {
2747     solver->parameters.eligibility_trace_mode = RIL_E_REPLACE;
2748   }
2749   else
2750   {
2751     solver->parameters.eligibility_trace_mode = RIL_E_ACCUMULATE;
2752   }
2753
2754   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_SOCIAL_WELFARE", &string))
2755   {
2756     solver->parameters.social_welfare = !strcmp (string, "NASH") ? RIL_WELFARE_NASH : RIL_WELFARE_EGALITARIAN;
2757     GNUNET_free (string);
2758   }
2759   else
2760   {
2761     solver->parameters.social_welfare = RIL_DEFAULT_WELFARE;
2762   }
2763
2764   solver->env = env;
2765   sf.cls = solver;
2766   sf.s_add = &GAS_ril_address_add;
2767   sf.s_address_update_property = &GAS_ril_address_property_changed;
2768   sf.s_get = &GAS_ril_get_preferred_address;
2769   sf.s_get_stop = &GAS_ril_stop_get_preferred_address;
2770   sf.s_pref = &GAS_ril_address_change_preference;
2771   sf.s_feedback = &GAS_ril_address_preference_feedback;
2772   sf.s_del = &GAS_ril_address_delete;
2773   sf.s_bulk_start = &GAS_ril_bulk_start;
2774   sf.s_bulk_stop = &GAS_ril_bulk_stop;
2775
2776   solver->networks_count = env->network_count;
2777   solver->network_entries = GNUNET_malloc (env->network_count * sizeof (struct RIL_Scope));
2778   solver->step_count = 0;
2779   solver->done = GNUNET_NO;
2780
2781   for (c = 0; c < env->network_count; c++)
2782   {
2783     cur = &solver->network_entries[c];
2784     cur->type = c;
2785     cur->bw_in_available = env->in_quota[c];
2786     cur->bw_out_available = env->out_quota[c];
2787     LOG (GNUNET_ERROR_TYPE_DEBUG,
2788          "init()  Quotas for %s network:  IN %llu - OUT %llu\n",
2789          GNUNET_ATS_print_network_type(cur->type),
2790          cur->bw_in_available/1024,
2791          cur->bw_out_available/1024);
2792   }
2793
2794   LOG(GNUNET_ERROR_TYPE_DEBUG, "init()  Parameters:\n");
2795   LOG(GNUNET_ERROR_TYPE_DEBUG, "init()  Algorithm = %s, alpha = %f, beta = %f, lambda = %f\n",
2796       solver->parameters.algorithm ? "Q" : "SARSA",
2797       solver->parameters.alpha,
2798       solver->parameters.beta,
2799       solver->parameters.lambda);
2800   LOG(GNUNET_ERROR_TYPE_DEBUG, "init()  exploration_ratio = %f, temperature = %f, ActionSelection = %s\n",
2801       solver->parameters.epsilon,
2802       solver->parameters.temperature,
2803       solver->parameters.select ? "EGREEDY" : "SOFTMAX");
2804   LOG(GNUNET_ERROR_TYPE_DEBUG, "init()  RBF_DIVISOR = %llu\n",
2805       solver->parameters.rbf_divisor);
2806
2807   return &sf;
2808 }
2809
2810
2811 /**
2812  * Exit point for the plugin
2813  *
2814  * @param cls the solver handle
2815  */
2816 void *
2817 libgnunet_plugin_ats_ril_done (void *cls)
2818 {
2819   struct GNUNET_ATS_SolverFunctions *sf = cls;
2820   struct GAS_RIL_Handle *s = sf->cls;
2821   struct RIL_Peer_Agent *cur_agent;
2822   struct RIL_Peer_Agent *next_agent;
2823
2824   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_done() Shutting down RIL solver\n");
2825
2826   s->done = GNUNET_YES;
2827
2828   cur_agent = s->agents_head;
2829   while (NULL != cur_agent)
2830   {
2831     next_agent = cur_agent->next;
2832     GNUNET_CONTAINER_DLL_remove(s->agents_head, s->agents_tail, cur_agent);
2833     agent_die (s, cur_agent);
2834     cur_agent = next_agent;
2835   }
2836
2837   if (NULL != s->step_next_task_id)
2838   {
2839     GNUNET_SCHEDULER_cancel (s->step_next_task_id);
2840   }
2841   GNUNET_free(s->network_entries);
2842   GNUNET_free(s);
2843
2844   return NULL;
2845 }
2846
2847
2848 /* end of plugin_ats_ril.c */