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