added preferences to state vector
[oweals/gnunet.git] / src / ats / libgnunet_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/libgnunet_plugin_ats_ril.c
23  * @brief ATS reinforcement learning solver
24  * @author Fabian Oehlmann
25  * @author Matthias Wachs
26  */
27 #include "libgnunet_plugin_ats_ril.h"
28
29 #define LOG(kind,...) GNUNET_log_from (kind, "ats-ril",__VA_ARGS__)
30
31 #define RIL_ACTION_INVALID -1
32 #define RIL_FEATURES_ADDRESS_COUNT (3 + GNUNET_ATS_QualityPropertiesCount)
33 #define RIL_FEATURES_NETWORK_COUNT 4
34 #define RIL_INTERVAL_EXPONENT 10
35
36 #define RIL_DEFAULT_STEP_TIME_MIN GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500)
37 #define RIL_DEFAULT_STEP_TIME_MAX GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 3000)
38 #define RIL_DEFAULT_ALGORITHM RIL_ALGO_SARSA
39 #define RIL_DEFAULT_DISCOUNT_BETA 0.7
40 #define RIL_DEFAULT_GRADIENT_STEP_SIZE 0.3
41 #define RIL_DEFAULT_TRACE_DECAY 0.5
42 #define RIL_DEFAULT_EXPLORE_RATIO 0.1
43
44 /**
45  * ATS reinforcement learning solver
46  *
47  * General description
48  */
49
50 /**
51  * The actions, how an agent can manipulate the current assignment. I.e. how the bandwidth can be
52  * changed for the currently chosen address. Not depicted in the enum are the actions of switching
53  * to a particular address. The action of switching to address with index i is depicted by the
54  * number (RIL_ACTION_TYPE_NUM + i).
55  */
56 enum RIL_Action_Type
57 {
58   RIL_ACTION_NOTHING = 0,
59   RIL_ACTION_BW_IN_DBL = 1,
60   RIL_ACTION_BW_IN_HLV = 2,
61   RIL_ACTION_BW_IN_INC = 3,
62   RIL_ACTION_BW_IN_DEC = 4,
63   RIL_ACTION_BW_OUT_DBL = 5,
64   RIL_ACTION_BW_OUT_HLV = 6,
65   RIL_ACTION_BW_OUT_INC = 7,
66   RIL_ACTION_BW_OUT_DEC = 8,
67   RIL_ACTION_TYPE_NUM = 9
68 };
69
70 enum RIL_Algorithm
71 {
72   RIL_ALGO_SARSA = 0,
73   RIL_ALGO_Q = 1
74 };
75
76 enum RIL_E_Modification
77 {
78   RIL_E_SET,
79   RIL_E_ZERO,
80   RIL_E_ACCUMULATE,
81   RIL_E_REPLACE
82 };
83
84 /**
85  * Global learning parameters
86  */
87 struct RIL_Learning_Parameters
88 {
89   /**
90    * The TD-algorithm to use
91    */
92   enum RIL_Algorithm algorithm;
93
94   /**
95    * Learning discount factor in the TD-update
96    */
97   double beta;
98
99   /**
100    * Gradient-descent step-size
101    */
102   double alpha;
103
104   /**
105    * Trace-decay factor for eligibility traces
106    */
107   double lambda;
108
109   /**
110    *
111    */
112   double explore_ratio;
113
114   /**
115    * Minimal interval time between steps in milliseconds
116    */
117   struct GNUNET_TIME_Relative step_time_min;
118
119   /**
120    * Maximum interval time between steps in milliseconds
121    */
122   struct GNUNET_TIME_Relative step_time_max;
123 };
124
125 /**
126  * Wrapper for addresses to store them in agent's linked list
127  */
128 struct RIL_Address_Wrapped
129 {
130   /**
131    * Next in DLL
132    */
133   struct RIL_Address_Wrapped *next;
134
135   /**
136    * Previous in DLL
137    */
138   struct RIL_Address_Wrapped *prev;
139
140   /**
141    * The address
142    */
143   struct ATS_Address *address_naked;
144 };
145
146 struct RIL_Peer_Agent
147 {
148   /**
149    * Next agent in solver's linked list
150    */
151   struct RIL_Peer_Agent *next;
152
153   /**
154    * Previous agent in solver's linked list
155    */
156   struct RIL_Peer_Agent *prev;
157
158   /**
159    * Environment handle
160    */
161   struct GAS_RIL_Handle *envi;
162
163   /**
164    * Peer ID
165    */
166   struct GNUNET_PeerIdentity peer;
167
168   /**
169    * Whether the agent is active or not
170    */
171   int is_active;
172
173   /**
174    * Number of performed time-steps
175    */
176   unsigned long long step_count;
177
178   /**
179    * Experience matrix W
180    */
181   double ** W;
182
183   /**
184    * Number of rows of W / Number of state-vector features
185    */
186   unsigned int m;
187
188   /**
189    * Number of columns of W / Number of actions
190    */
191   unsigned int n;
192
193   /**
194    * Last perceived state feature vector
195    */
196   double * s_old;
197
198   /**
199    * Last chosen action
200    */
201   int a_old;
202
203   /**
204    * Eligibility trace vector
205    */
206   double * e;
207
208   /**
209    * Address in use
210    */
211   struct ATS_Address * address_inuse;
212
213   /**
214    * Head of addresses DLL
215    */
216   struct RIL_Address_Wrapped * addresses_head;
217
218   /**
219    * Tail of addresses DLL
220    */
221   struct RIL_Address_Wrapped * addresses_tail;
222
223   /**
224    * Inbound bandwidth assigned by the agent
225    */
226   unsigned long long bw_in;
227
228   /**
229    * Outbound bandwidth assigned by the agent
230    */
231   unsigned long long bw_out;
232
233   /**
234    * Flag whether a suggestion has to be issued
235    */
236   int suggestion_issue;
237
238   /**
239    * The address which has to be issued ()
240    */
241   struct ATS_Address * suggestion_address;
242 };
243
244 struct RIL_Network
245 {
246   /**
247    * ATS network type
248    */
249   enum GNUNET_ATS_Network_Type type;
250
251   /**
252    * Total available inbound bandwidth
253    */
254   unsigned long long bw_in_available;
255
256   /**
257    * Total available outbound bandwidth
258    */
259   unsigned long long bw_out_available;
260 };
261
262 /**
263  * A handle for the reinforcement learning solver
264  */
265 struct GAS_RIL_Handle
266 {
267   /**
268    * The solver-plugin environment of the solver-plugin API
269    */
270   struct GNUNET_ATS_PluginEnvironment *plugin_envi;
271
272   /**
273    * Statistics handle
274    */
275   struct GNUNET_STATISTICS_Handle *stats;
276
277   /**
278    * Number of performed steps
279    */
280   unsigned long long step_count;
281
282   /**
283    * Timestamp for the last time-step
284    */
285   struct GNUNET_TIME_Absolute step_time_last;
286
287   /**
288    * Task identifier of the next time-step to be executed
289    */
290   GNUNET_SCHEDULER_TaskIdentifier step_next_task_id;
291
292   /**
293    * Whether a step is already scheduled
294    */
295   int task_pending;
296
297   /**
298    * Variable discount factor, dependent on time between steps
299    */
300   double discount_variable;
301
302   /**
303    * Integrated variable discount factor, dependent on time between steps
304    */
305   double discount_integrated;
306
307   /**
308    * State vector for networks for the current step
309    */
310   double *state_networks;
311
312   /**
313    * Lock for bulk operations
314    */
315   int bulk_lock;
316
317   /**
318    * Number of changes during a lock
319    */
320   int bulk_changes;
321
322   /**
323    * Learning parameters
324    */
325   struct RIL_Learning_Parameters parameters;
326
327   /**
328    * Array of networks with global assignment state
329    */
330   struct RIL_Network * network_entries;
331
332   /**
333    * Networks count
334    */
335   unsigned int networks_count;
336
337   /**
338    * List of active peer-agents
339    */
340   struct RIL_Peer_Agent * agents_head;
341   struct RIL_Peer_Agent * agents_tail;
342 };
343
344 /*
345  *  Private functions
346  *  ---------------------------
347  */
348
349 /**
350  * Estimate the current action-value for state s and action a
351  *
352  * @param agent agent performing the estimation
353  * @param state s
354  * @param action a
355  * @return estimation value
356  */
357 static double
358 agent_estimate_q (struct RIL_Peer_Agent *agent, double *state, int action)
359 {
360   int i;
361   double result = 0;
362
363   for (i = 0; i < agent->m; i++)
364   {
365     result += state[i] * agent->W[action][i];
366   }
367
368   return result;
369 }
370
371 /**
372  * Decide whether to do exploration (i.e. taking a new action) or exploitation (i.e. taking the
373  * currently estimated best action) in the current step
374  *
375  * @param agent agent performing the step
376  * @return yes, if exploring
377  */
378 static int
379 agent_decide_exploration (struct RIL_Peer_Agent *agent)
380 {
381   //TODO? Future Work: Improve exploration/exploitation trade-off by different mechanisms than e-greedy
382   double r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
383       UINT32_MAX) / (double) UINT32_MAX;
384
385   if (r < agent->envi->parameters.explore_ratio)
386   {
387     return GNUNET_YES;
388   }
389   return GNUNET_NO;
390 }
391
392   /**
393    * Get the index of the address in the agent's list.
394    *
395    * @param agent agent handle
396    * @param address address handle
397    * @return the index, starting with zero
398    */
399 static int
400 agent_address_get_index (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
401 {
402   int i;
403   struct RIL_Address_Wrapped *cur;
404
405   i = -1;
406   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
407   {
408     i++;
409     if (cur->address_naked == address)
410     {
411       return i;
412     }
413   }
414
415   return i;
416 }
417
418 /**
419  * Gets the wrapped address from the agent's list
420  *
421  * @param agent agent handle
422  * @param address address handle
423  * @return wrapped address
424  */
425 static struct RIL_Address_Wrapped *
426 agent_address_get (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
427 {
428   struct RIL_Address_Wrapped *cur;
429
430   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
431   {
432     if (cur->address_naked == address)
433     {
434       return cur;
435     }
436   }
437
438   return NULL ;
439 }
440
441 /**
442  * Gets the action, with the maximal estimated Q-value (i.e. the one currently estimated to bring the
443  * most reward in the future)
444  *
445  * @param agent agent performing the calculation
446  * @param state the state from which to take the action
447  * @return the action promising most future reward
448  */
449 static int
450 agent_get_action_best (struct RIL_Peer_Agent *agent, double *state)
451 {
452   int i;
453   int max_i = RIL_ACTION_INVALID;
454   double cur_q;
455   double max_q = -DBL_MAX;
456
457   for (i = 0; i < agent->n; i++)
458   {
459     cur_q = agent_estimate_q (agent, state, i);
460     if (cur_q > max_q)
461     {
462       max_q = cur_q;
463       max_i = i;
464     }
465   }
466
467   GNUNET_assert(RIL_ACTION_INVALID != max_i);
468
469   return max_i;
470 }
471
472 /**
473  * Gets any action, to explore the action space from that state
474  *
475  * @param agent agent performing the calculation
476  * @param state the state from which to take the action
477  * @return any action
478  */
479 static int
480 agent_get_action_explore (struct RIL_Peer_Agent *agent, double *state)
481 {
482   // TODO?: Future Work: Choose the action for exploration, which has been explored the least in this state
483   return GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, agent->n);
484 }
485
486 /**
487  * Updates the weights (i.e. coefficients) of the weight vector in matrix W for action a
488  *
489  * @param agent the agent performing the update
490  * @param reward the reward received for the last action
491  * @param s_next the new state, the last step got the agent into
492  * @param a_prime the new
493  */
494 static void
495 agent_update_weights (struct RIL_Peer_Agent *agent, double reward, double *s_next, int a_prime)
496 {
497   int i;
498   double delta;
499   double *theta = agent->W[agent->a_old];
500
501   delta = agent->envi->discount_integrated * reward; //reward
502   delta += agent->envi->discount_variable * agent_estimate_q (agent, s_next, a_prime); //discounted future value
503   delta -= agent_estimate_q (agent, agent->s_old, agent->a_old); //one step
504   for (i = 0; i < agent->m; i++)
505   {
506     theta[i] += agent->envi->parameters.alpha * delta * agent->e[i];
507   }
508 }
509
510 /**
511  * Changes the eligibility trace vector e in various manners:
512  * RIL_E_ACCUMULATE - adds 1 to each component as in accumulating eligibility traces
513  * RIL_E_REPLACE - resets each component to 1 as in replacing traces
514  * RIL_E_SET - multiplies e with discount factor and lambda as in the update rule
515  * RIL_E_ZERO - sets e to 0 as in Watkin's Q-learning algorithm when exploring and when initializing
516  *
517  * @param agent the agent handle
518  * @param mod the kind of modification
519  */
520 static void
521 agent_modify_eligibility (struct RIL_Peer_Agent *agent, enum RIL_E_Modification mod)
522 {
523   int i;
524   double *e = agent->e;
525
526   for (i = 0; i < agent->m; i++)
527   {
528     switch (mod)
529     {
530     case RIL_E_ACCUMULATE:
531       e[i] += 1;
532       break;
533     case RIL_E_REPLACE:
534       e[i] = 1;
535       break;
536     case RIL_E_SET:
537       e[i] *= agent->envi->discount_variable * agent->envi->parameters.lambda;
538       break;
539     case RIL_E_ZERO:
540       e[i] = 0;
541       break;
542     }
543   }
544 }
545
546 static void
547 ril_inform (struct GAS_RIL_Handle *solver,
548     enum GAS_Solver_Operation op,
549     enum GAS_Solver_Status stat)
550 {
551   if (NULL != solver->plugin_envi->info_cb)
552     solver->plugin_envi->info_cb (solver->plugin_envi->info_cb_cls, op, stat, GAS_INFO_NONE);
553 }
554
555 /**
556  * Changes the active assignment suggestion of the handler and invokes the bw_changed callback to
557  * notify ATS of its new decision
558  *
559  * @param solver solver handle
560  * @param agent agent handle
561  * @param new_address the address which is to be used
562  * @param new_bw_in the new amount of inbound bandwidth set for this address
563  * @param new_bw_out the new amount of outbound bandwidth set for this address
564  * @param silent disables invocation of the bw_changed callback, if GNUNET_YES
565  */
566 static void
567 envi_set_active_suggestion (struct GAS_RIL_Handle *solver,
568     struct RIL_Peer_Agent *agent,
569     struct ATS_Address *new_address,
570     unsigned long long new_bw_in,
571     unsigned long long new_bw_out,
572     int silent)
573 {
574   int notify = GNUNET_NO;
575
576   LOG(GNUNET_ERROR_TYPE_DEBUG, "    set_active_suggestion() for peer '%s'\n", GNUNET_i2s (&agent->peer));
577
578   //address change
579   if (agent->address_inuse != new_address)
580   {
581     if (NULL != agent->address_inuse)
582     {
583       agent->address_inuse->active = GNUNET_NO;
584       agent->address_inuse->assigned_bw_in.value__ = htonl (0);
585       agent->address_inuse->assigned_bw_out.value__ = htonl (0);
586     }
587     if (NULL != new_address)
588     {
589       LOG(GNUNET_ERROR_TYPE_DEBUG, "    set address active: %s\n", agent->is_active ? "yes" : "no");
590       new_address->active = agent->is_active;
591       new_address->assigned_bw_in.value__ = htonl (agent->bw_in);
592       new_address->assigned_bw_out.value__ = htonl (agent->bw_out);
593     }
594     notify |= GNUNET_YES;
595   }
596
597   if (new_address)
598   {
599     //activity change
600     if (new_address->active != agent->is_active)
601     {
602       new_address->active = agent->is_active;
603       notify |= GNUNET_YES;
604     }
605
606     //bw change
607     if (agent->bw_in != new_bw_in)
608     {
609       agent->bw_in = new_bw_in;
610       new_address->assigned_bw_in.value__ = htonl (new_bw_in);
611       notify |= GNUNET_YES;
612     }
613     if (agent->bw_out != new_bw_out)
614     {
615       agent->bw_out = new_bw_out;
616       new_address->assigned_bw_out.value__ = htonl (new_bw_out);
617       notify |= GNUNET_YES;
618     }
619   }
620
621   if (notify && agent->is_active && (GNUNET_NO == silent))
622   {
623     if (new_address)
624     {
625       LOG(GNUNET_ERROR_TYPE_DEBUG, "    envi_set_active_suggestion() notify\n");
626       agent->suggestion_issue = GNUNET_YES;
627       agent->suggestion_address = new_address;
628     }
629     else if (agent->address_inuse)
630     {
631       //disconnect case, no new address
632       GNUNET_assert(0 == ntohl (agent->address_inuse->assigned_bw_in.value__));
633       GNUNET_assert(0 == ntohl (agent->address_inuse->assigned_bw_out.value__));
634       agent->bw_in = 0;
635       agent->bw_out = 0;
636
637       agent->suggestion_issue = GNUNET_YES;
638       agent->suggestion_address = agent->address_inuse;
639     }
640   }
641   agent->address_inuse = new_address;
642 }
643
644 static unsigned long long
645 ril_network_get_assigned (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type type, int direction_in)
646 {
647   struct RIL_Peer_Agent *cur;
648   struct RIL_Network *net;
649   unsigned long long sum = 0;
650
651   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
652   {
653     if (cur->is_active && cur->address_inuse)
654     {
655       net = cur->address_inuse->solver_information;
656       if (net->type == type)
657       {
658         if (direction_in)
659           sum += cur->bw_in;
660         else
661           sum += cur->bw_out;
662       }
663     }
664   }
665
666   return sum;
667 }
668
669 static void
670 envi_state_networks (struct GAS_RIL_Handle *solver)
671 {
672   int i;
673   struct RIL_Network net;
674
675   for (i = 0; i < solver->networks_count; i++)
676   {
677     net = solver->network_entries[i];
678     solver->state_networks[i * RIL_FEATURES_NETWORK_COUNT + 0] = (double) ril_network_get_assigned(solver, net.type, GNUNET_YES);
679     solver->state_networks[i * RIL_FEATURES_NETWORK_COUNT + 1] = (double) net.bw_in_available;
680     solver->state_networks[i * RIL_FEATURES_NETWORK_COUNT + 2] = (double) ril_network_get_assigned(solver, net.type, GNUNET_NO);
681     solver->state_networks[i * RIL_FEATURES_NETWORK_COUNT + 3] = (double) net.bw_out_available;
682   }
683 }
684
685 /**
686  * Allocates a state vector and fills it with the features present
687  * @param solver the solver handle
688  * @param agent the agent handle
689  * @return pointer to the state vector
690  */
691 static double *
692 envi_get_state (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
693 {
694   int i;
695   int k;
696   double *state = GNUNET_malloc (sizeof (double) * agent->m);
697   struct RIL_Address_Wrapped *cur_address;
698   const double *preferences;
699   const double *properties;
700
701   //copy global networks state
702   for (i = 0; i < solver->networks_count; i++)
703   {
704     state[i * RIL_FEATURES_NETWORK_COUNT + 0] = solver->state_networks[i * RIL_FEATURES_NETWORK_COUNT + 0];
705     state[i * RIL_FEATURES_NETWORK_COUNT + 1] = solver->state_networks[i * RIL_FEATURES_NETWORK_COUNT + 1];
706     state[i * RIL_FEATURES_NETWORK_COUNT + 2] = solver->state_networks[i * RIL_FEATURES_NETWORK_COUNT + 2];
707     state[i * RIL_FEATURES_NETWORK_COUNT + 3] = solver->state_networks[i * RIL_FEATURES_NETWORK_COUNT + 3];
708   }
709
710   //get peer features
711   i = i * RIL_FEATURES_NETWORK_COUNT;
712   preferences = solver->plugin_envi->get_preferences (solver->plugin_envi->get_preference_cls,
713         &agent->peer);
714   for (k = 0; k < GNUNET_ATS_PreferenceCount; k++)
715   {
716     state[i++] = preferences[k];
717   }
718
719   //get address specific features
720   for (cur_address = agent->addresses_head; NULL != cur_address; cur_address = cur_address->next)
721   {
722     //when changing the number of address specific state features, change RIL_FEATURES_ADDRESS_COUNT macro
723     state[i++] = cur_address->address_naked->active;
724     state[i++] = cur_address->address_naked->active ? agent->bw_in : 0;
725     state[i++] = cur_address->address_naked->active ? agent->bw_out : 0;
726     properties = solver->plugin_envi->get_property (solver->plugin_envi->get_property_cls,
727         cur_address->address_naked);
728     for (k = 0; k < GNUNET_ATS_QualityPropertiesCount; k++)
729     {
730       state[i++] = properties[k];
731     }
732   }
733
734   return state;
735 }
736
737 /**
738  * For all networks a peer has an address in, this gets the maximum bandwidth which could
739  * theoretically be available in one of the networks. This is used for bandwidth normalization.
740  *
741  * @param agent the agent handle
742  * @param direction_in whether the inbound bandwidth should be considered. Returns the maximum outbound bandwidth if GNUNET_NO
743  */
744 static long long unsigned
745 ril_get_max_bw (struct RIL_Peer_Agent *agent, int direction_in)
746 {
747   /*
748    * get the maximum bandwidth possible for a peer, e.g. among all addresses which addresses'
749    * network could provide the maximum bandwidth if all that bandwidth was used on that one peer.
750    */
751   int max = 0;
752   struct RIL_Address_Wrapped *cur;
753   struct RIL_Network *net;
754
755   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
756   {
757     net = cur->address_naked->solver_information;
758     if (direction_in)
759     {
760       if (net->bw_in_available > max)
761       {
762         max = net->bw_in_available;
763       }
764     }
765     else
766     {
767       if (net->bw_out_available > max)
768       {
769         max = net->bw_out_available;
770       }
771     }
772   }
773   return max;
774 }
775
776 /**
777  * Get the index of the quality-property in question
778  *
779  * @param type the quality property type
780  * @return the index
781  */
782 static int
783 ril_find_property_index (uint32_t type)
784 {
785   int existing_types[] = GNUNET_ATS_QualityProperties;
786   int c;
787   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
788     if (existing_types[c] == type)
789       return c;
790   return GNUNET_SYSERR;
791 }
792
793 static int
794 ril_get_atsi (struct ATS_Address *address, uint32_t type)
795 {
796   int c1;
797   GNUNET_assert(NULL != address);
798
799   if ((NULL == address->atsi) || (0 == address->atsi_count))
800     return 0;
801
802   for (c1 = 0; c1 < address->atsi_count; c1++)
803   {
804     if (ntohl (address->atsi[c1].type) == type)
805       return ntohl (address->atsi[c1].value);
806   }
807   return 0;
808 }
809
810 static double
811 envi_reward_global (struct GAS_RIL_Handle *solver)
812 {
813   int i;
814   struct RIL_Network net;
815   unsigned int sum_in_available = 0;
816   unsigned int sum_out_available = 0;
817   unsigned int sum_in_assigned = 0;
818   unsigned int sum_out_assigned = 0;
819   double ratio_in;
820   double ratio_out;
821
822   for (i = 0; i < solver->networks_count; i++)
823   {
824     net = solver->network_entries[i];
825     sum_in_available += net.bw_in_available;
826     sum_in_assigned += ril_network_get_assigned(solver, net.type, GNUNET_YES);
827     sum_out_available += net.bw_out_available;
828     sum_out_assigned += ril_network_get_assigned(solver, net.type, GNUNET_NO);
829   }
830
831   ratio_in = ((double) sum_in_assigned) / ((double) sum_in_available);
832   ratio_out = ((double) sum_out_assigned) / ((double) sum_out_available);
833
834   // global reward in [1,2]
835   return ((ratio_in + ratio_out) / 2) + 1;
836 }
837
838 static double
839 envi_reward_local (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
840 {
841   const double *preferences;
842   const double *properties;
843   int prop_index;
844   double pref_match = 0;
845   double bw_norm;
846   double dl_norm;
847
848   preferences = solver->plugin_envi->get_preferences (solver->plugin_envi->get_preference_cls,
849       &agent->peer);
850   properties = solver->plugin_envi->get_property (solver->plugin_envi->get_property_cls,
851       agent->address_inuse);
852
853   // delay in [0,1]
854   prop_index = ril_find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
855   dl_norm = 2 - properties[prop_index]; //invert property as we want to maximize for lower latencies
856
857   // utilization in [0,1]
858   bw_norm = ((ril_get_atsi (agent->address_inuse, GNUNET_ATS_UTILIZATION_IN)
859       / ril_get_max_bw (agent, GNUNET_YES))
860       + (ril_get_atsi (agent->address_inuse, GNUNET_ATS_UTILIZATION_OUT)
861           / ril_get_max_bw (agent, GNUNET_NO))) / 2;
862
863   // preference matching in [0,4]
864   pref_match += (preferences[GNUNET_ATS_PREFERENCE_LATENCY] * dl_norm);
865   pref_match += (preferences[GNUNET_ATS_PREFERENCE_BANDWIDTH] * bw_norm);
866
867   // local reward in [1,2]
868   return (pref_match / 4) +1;
869 }
870
871 /**
872  * Gets the reward for the last performed step, which is calculated in equal
873  * parts from the local (the peer specific) and the global (for all peers
874  * identical) reward.
875  *
876  * @param solver the solver handle
877  * @param agent the agent handle
878  * @return the reward
879  */
880 static double
881 envi_get_reward (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
882 {
883   struct RIL_Network *net;
884   double reward = 0;
885
886   //punish overutilization
887   net = agent->address_inuse->solver_information;
888   if ((ril_network_get_assigned(solver, net->type, GNUNET_YES) > net->bw_in_available)
889       || (ril_network_get_assigned(solver, net->type, GNUNET_NO) > net->bw_out_available))
890   {
891     return 0;
892   }
893
894   reward += envi_reward_global (solver);
895   reward += envi_reward_local (solver, agent);
896   return reward * 0.5;
897 }
898
899 /**
900  * Doubles the bandwidth for the active address
901  *
902  * @param solver solver handle
903  * @param agent agent handle
904  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise the outbound bandwidth
905  */
906 static void
907 envi_action_bw_double (struct GAS_RIL_Handle *solver,
908     struct RIL_Peer_Agent *agent,
909     int direction_in)
910 {
911   unsigned long long new_bw;
912
913   if (direction_in)
914   {
915     new_bw = agent->bw_in * 2;
916     if (new_bw < agent->bw_in)
917       new_bw = ULLONG_MAX;
918     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw,
919         agent->bw_out, GNUNET_NO);
920   }
921   else
922   {
923     new_bw = agent->bw_out * 2;
924     if (new_bw < agent->bw_out)
925       new_bw = ULLONG_MAX;
926     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
927         new_bw, GNUNET_NO);
928   }
929 }
930
931 /**
932  * Cuts the bandwidth for the active address in half. The least amount of bandwidth suggested, is
933  * the minimum bandwidth for a peer, in order to not invoke a disconnect.
934  *
935  * @param solver solver handle
936  * @param agent agent handle
937  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
938  * bandwidth
939  */
940 static void
941 envi_action_bw_halven (struct GAS_RIL_Handle *solver,
942     struct RIL_Peer_Agent *agent,
943     int direction_in)
944 {
945   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
946   unsigned long long new_bw;
947
948   if (direction_in)
949   {
950     new_bw = agent->bw_in / 2;
951     if (new_bw < min_bw || new_bw > agent->bw_in)
952       new_bw = min_bw;
953     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
954         GNUNET_NO);
955   }
956   else
957   {
958     new_bw = agent->bw_out / 2;
959     if (new_bw < min_bw || new_bw > agent->bw_out)
960       new_bw = min_bw;
961     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
962         GNUNET_NO);
963   }
964 }
965
966 /**
967  * Increases the bandwidth by 5 times the minimum bandwidth for the active address.
968  *
969  * @param solver solver handle
970  * @param agent agent handle
971  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
972  * bandwidth
973  */
974 static void
975 envi_action_bw_inc (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
976 {
977   unsigned long long new_bw;
978   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
979
980   if (direction_in)
981   {
982     new_bw = agent->bw_in + (5 * min_bw);
983     if (new_bw < agent->bw_in)
984       new_bw = ULLONG_MAX;
985     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw,
986         agent->bw_out, GNUNET_NO);
987   }
988   else
989   {
990     new_bw = agent->bw_out + (5 * min_bw);
991     if (new_bw < agent->bw_out)
992       new_bw = ULLONG_MAX;
993     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
994         new_bw, GNUNET_NO);
995   }
996 }
997
998 /**
999  * Decreases the bandwidth by 5 times the minimum bandwidth for the active address. The least amount
1000  * of bandwidth suggested, is the minimum bandwidth for a peer, in order to not invoke a disconnect.
1001  *
1002  * @param solver solver handle
1003  * @param agent agent handle
1004  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
1005  * bandwidth
1006  */
1007 static void
1008 envi_action_bw_dec (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
1009 {
1010   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1011   unsigned long long new_bw;
1012
1013   if (direction_in)
1014   {
1015     new_bw = agent->bw_in - (5 * min_bw);
1016     if (new_bw < min_bw || new_bw > agent->bw_in)
1017       new_bw = min_bw;
1018     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
1019         GNUNET_NO);
1020   }
1021   else
1022   {
1023     new_bw = agent->bw_out - (5 * min_bw);
1024     if (new_bw < min_bw || new_bw > agent->bw_in)
1025       new_bw = min_bw;
1026     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
1027         GNUNET_NO);
1028   }
1029 }
1030
1031 /**
1032  * Switches to the address given by its index
1033  *
1034  * @param solver solver handle
1035  * @param agent agent handle
1036  * @param address_index index of the address as it is saved in the agent's list, starting with zero
1037  */
1038 static void
1039 envi_action_address_switch (struct GAS_RIL_Handle *solver,
1040     struct RIL_Peer_Agent *agent,
1041     unsigned int address_index)
1042 {
1043   struct RIL_Address_Wrapped *cur;
1044   int i = 0;
1045
1046   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
1047   {
1048     if (i == address_index)
1049     {
1050       envi_set_active_suggestion (solver, agent, cur->address_naked, agent->bw_in, agent->bw_out,
1051           GNUNET_NO);
1052       return;
1053     }
1054
1055     i++;
1056   }
1057
1058   //no address with address_index exists, in this case this action should not be callable
1059   GNUNET_assert(GNUNET_NO);
1060 }
1061
1062 /**
1063  * Puts the action into effect by calling the according function
1064  *
1065  * @param solver the solver handle
1066  * @param agent the action handle
1067  * @param action the action to perform by the solver
1068  */
1069 static void
1070 envi_do_action (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int action)
1071 {
1072   int address_index;
1073
1074   switch (action)
1075   {
1076   case RIL_ACTION_NOTHING:
1077     break;
1078   case RIL_ACTION_BW_IN_DBL:
1079     envi_action_bw_double (solver, agent, GNUNET_YES);
1080     break;
1081   case RIL_ACTION_BW_IN_HLV:
1082     envi_action_bw_halven (solver, agent, GNUNET_YES);
1083     break;
1084   case RIL_ACTION_BW_IN_INC:
1085     envi_action_bw_inc (solver, agent, GNUNET_YES);
1086     break;
1087   case RIL_ACTION_BW_IN_DEC:
1088     envi_action_bw_dec (solver, agent, GNUNET_YES);
1089     break;
1090   case RIL_ACTION_BW_OUT_DBL:
1091     envi_action_bw_double (solver, agent, GNUNET_NO);
1092     break;
1093   case RIL_ACTION_BW_OUT_HLV:
1094     envi_action_bw_halven (solver, agent, GNUNET_NO);
1095     break;
1096   case RIL_ACTION_BW_OUT_INC:
1097     envi_action_bw_inc (solver, agent, GNUNET_NO);
1098     break;
1099   case RIL_ACTION_BW_OUT_DEC:
1100     envi_action_bw_dec (solver, agent, GNUNET_NO);
1101     break;
1102   default:
1103     if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action
1104     {
1105       address_index = action - RIL_ACTION_TYPE_NUM;
1106
1107       GNUNET_assert(address_index >= 0);
1108       GNUNET_assert(
1109           address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked));
1110
1111       envi_action_address_switch (solver, agent, address_index);
1112       break;
1113     }
1114     // error - action does not exist
1115     GNUNET_assert(GNUNET_NO);
1116   }
1117 }
1118
1119 /**
1120  * Performs one step of the Markov Decision Process. Other than in the literature the step starts
1121  * after having done the last action a_old. It observes the new state s_next and the reward
1122  * received. Then the coefficient update is done according to the SARSA or Q-learning method. The
1123  * next action is put into effect.
1124  *
1125  * @param agent the agent performing the step
1126  */
1127 static void
1128 agent_step (struct RIL_Peer_Agent *agent)
1129 {
1130   int a_next = RIL_ACTION_INVALID;
1131   double *s_next;
1132   double reward;
1133
1134   LOG(GNUNET_ERROR_TYPE_DEBUG, "    agent_step() Peer '%s', algorithm %s\n",
1135       GNUNET_i2s (&agent->peer),
1136       agent->envi->parameters.algorithm ? "Q" : "SARSA");
1137
1138   s_next = envi_get_state (agent->envi, agent);
1139   reward = envi_get_reward (agent->envi, agent);
1140
1141   switch (agent->envi->parameters.algorithm)
1142   {
1143   case RIL_ALGO_SARSA:
1144     agent_modify_eligibility (agent, RIL_E_SET);
1145     if (agent_decide_exploration (agent))
1146     {
1147       a_next = agent_get_action_explore (agent, s_next);
1148     }
1149     else
1150     {
1151       a_next = agent_get_action_best (agent, s_next);
1152     }
1153     if (RIL_ACTION_INVALID != agent->a_old)
1154     {
1155       //updates weights with selected action (on-policy), if not first step
1156       agent_update_weights (agent, reward, s_next, a_next);
1157     }
1158     break;
1159
1160   case RIL_ALGO_Q:
1161     a_next = agent_get_action_best (agent, s_next);
1162     if (RIL_ACTION_INVALID != agent->a_old)
1163     {
1164       //updates weights with best action, disregarding actually selected action (off-policy), if not first step
1165       agent_update_weights (agent, reward, s_next, a_next);
1166     }
1167     if (agent_decide_exploration (agent))
1168     {
1169       a_next = agent_get_action_explore (agent, s_next);
1170       agent_modify_eligibility (agent, RIL_E_ZERO);
1171     }
1172     else
1173     {
1174       a_next = agent_get_action_best (agent, s_next);
1175       agent_modify_eligibility (agent, RIL_E_SET);
1176     }
1177     break;
1178   }
1179
1180   GNUNET_assert(RIL_ACTION_INVALID != a_next);
1181
1182   agent_modify_eligibility (agent, RIL_E_ACCUMULATE);
1183
1184   envi_do_action (agent->envi, agent, a_next);
1185
1186   GNUNET_free(agent->s_old);
1187   agent->s_old = s_next;
1188   agent->a_old = a_next;
1189
1190   agent->step_count += 1;
1191 }
1192
1193 static int
1194 ril_step (struct GAS_RIL_Handle *solver);
1195
1196 /**
1197  * Task for the scheduler, which performs one step and lets the solver know that
1198  * no further step is scheduled.
1199  *
1200  * @param cls the solver handle
1201  * @param tc the task context for the scheduler
1202  */
1203 static void
1204 ril_step_scheduler_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1205 {
1206   struct GAS_RIL_Handle *solver = cls;
1207
1208   solver->task_pending = GNUNET_NO;
1209   ril_step (solver);
1210 }
1211
1212 static double
1213 ril_get_used_resource_ratio (struct GAS_RIL_Handle *solver)
1214 {
1215   int i;
1216   struct RIL_Network net;
1217   unsigned long long sum_assigned = 0;
1218   unsigned long long sum_available = 0;
1219   double ratio;
1220
1221   for (i = 0; i < solver->networks_count; i++)
1222   {
1223     net = solver->network_entries[i];
1224     if (ril_network_get_assigned(solver, net.type, GNUNET_YES) > 0) //only consider scopes with an active address
1225     {
1226       sum_assigned += ril_network_get_assigned(solver, net.type, GNUNET_YES);
1227       sum_assigned += ril_network_get_assigned(solver, net.type, GNUNET_NO);
1228       sum_available += net.bw_in_available;
1229       sum_available += net.bw_out_available;
1230     }
1231   }
1232   if (sum_available > 0)
1233   {
1234     ratio = ((double) sum_assigned) / ((double) sum_available);
1235   }
1236   else
1237   {
1238     ratio = 0;
1239   }
1240
1241   return ratio > 1 ? 1 : ratio; //overutilization possible, cap at 1
1242 }
1243
1244 /**
1245  * Schedules the next global step in an adaptive way. The more resources are
1246  * left, the earlier the next step is scheduled. This serves the reactivity of
1247  * the solver to changed inputs.
1248  *
1249  * @param solver the solver handle
1250  */
1251 static void
1252 ril_step_schedule_next (struct GAS_RIL_Handle *solver)
1253 {
1254   double used_ratio;
1255   double factor;
1256   double y;
1257   double offset;
1258   struct GNUNET_TIME_Relative time_next;
1259
1260   if (solver->task_pending)
1261   {
1262     GNUNET_SCHEDULER_cancel (solver->step_next_task_id);
1263   }
1264
1265   used_ratio = ril_get_used_resource_ratio (solver);
1266
1267   GNUNET_assert(
1268       solver->parameters.step_time_min.rel_value_us
1269           < solver->parameters.step_time_max.rel_value_us);
1270
1271   factor = (double) GNUNET_TIME_relative_subtract (solver->parameters.step_time_max,
1272       solver->parameters.step_time_min).rel_value_us;
1273   offset = (double) solver->parameters.step_time_min.rel_value_us;
1274   y = factor * pow (used_ratio, RIL_INTERVAL_EXPONENT) + offset;
1275
1276   GNUNET_assert(y <= (double ) solver->parameters.step_time_max.rel_value_us);
1277   GNUNET_assert(y >= (double ) solver->parameters.step_time_min.rel_value_us);
1278
1279   time_next = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MICROSECONDS, (unsigned int) y);
1280
1281   solver->step_next_task_id = GNUNET_SCHEDULER_add_delayed (time_next, &ril_step_scheduler_task,
1282       solver);
1283   solver->task_pending = GNUNET_YES;
1284 }
1285
1286 /**
1287  * Triggers one step per agent
1288  * @param solver
1289  */
1290 static int
1291 ril_step (struct GAS_RIL_Handle *solver)
1292 {
1293   struct RIL_Peer_Agent *cur;
1294   struct GNUNET_TIME_Absolute time_now;
1295   struct GNUNET_TIME_Relative time_delta;
1296   double tau;
1297
1298   if (GNUNET_YES == solver->bulk_lock)
1299   {
1300     solver->bulk_changes++;
1301     return GNUNET_NO;
1302   }
1303
1304   ril_inform (solver, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS);
1305
1306   LOG(GNUNET_ERROR_TYPE_DEBUG, "    RIL step number %d\n", solver->step_count);
1307
1308   if (0 == solver->step_count)
1309   {
1310     solver->step_time_last = GNUNET_TIME_absolute_get ();
1311   }
1312
1313   //calculate tau, i.e. how many real valued time units have passed, one time unit is one minimum time step
1314   time_now = GNUNET_TIME_absolute_get ();
1315   time_delta = GNUNET_TIME_absolute_get_difference (solver->step_time_last, time_now);
1316   tau = ((double) time_delta.rel_value_us)
1317       / ((double) solver->parameters.step_time_min.rel_value_us);
1318   solver->step_time_last = time_now;
1319
1320   //calculate reward discounts (once per step for all agents)
1321   solver->discount_variable = pow (M_E, ((-1.) * ((double) solver->parameters.beta) * tau));
1322   solver->discount_integrated = (1 - solver->discount_variable)
1323       / ((double) solver->parameters.beta);
1324
1325   //calculate network state vector
1326   envi_state_networks(solver);
1327
1328   //trigger one step per active agent
1329   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1330   {
1331     if (cur->is_active && cur->address_inuse)
1332     {
1333       agent_step (cur);
1334     }
1335   }
1336
1337   solver->step_count += 1;
1338   ril_step_schedule_next (solver);
1339
1340   ril_inform (solver, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS);
1341
1342   ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, GAS_STAT_SUCCESS);
1343   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1344   {
1345     if (cur->suggestion_issue) {
1346       solver->plugin_envi->bandwidth_changed_cb(solver->plugin_envi->bw_changed_cb_cls, cur->suggestion_address);
1347       cur->suggestion_issue = GNUNET_NO;
1348     }
1349   }
1350   ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, GAS_STAT_SUCCESS);
1351
1352   return GNUNET_YES;
1353 }
1354
1355 static int
1356 ril_count_agents (struct GAS_RIL_Handle *solver)
1357 {
1358   int c = 0;
1359   struct RIL_Peer_Agent *cur_agent;
1360
1361   for (cur_agent = solver->agents_head; NULL != cur_agent; cur_agent = cur_agent->next)
1362   {
1363     c++;
1364   }
1365   return c;
1366 }
1367
1368 static void
1369 agent_w_start (struct RIL_Peer_Agent *agent)
1370 {
1371   int count;
1372   struct RIL_Peer_Agent *other;
1373   int i;
1374   int k;
1375
1376   count = ril_count_agents(agent->envi);
1377
1378   if (0 == count)
1379     return;
1380
1381   for (other = agent->envi->agents_head; NULL != other; other = other->next)
1382   {
1383     for (i = 0; i < agent->n; i++)
1384     {
1385       for (k = 0; k < agent->m; k++)
1386       {
1387         agent->W[i][k] += (other->W[i][k] / (double) count);
1388       }
1389     }
1390   }
1391 }
1392
1393 /**
1394  * Initialize an agent without addresses and its knowledge base
1395  *
1396  * @param s ril solver
1397  * @param peer the one in question
1398  * @return handle to the new agent
1399  */
1400 static struct RIL_Peer_Agent *
1401 agent_init (void *s, const struct GNUNET_PeerIdentity *peer)
1402 {
1403   int i;
1404   struct GAS_RIL_Handle * solver = s;
1405   struct RIL_Peer_Agent * agent = GNUNET_malloc (sizeof (struct RIL_Peer_Agent));
1406
1407   agent->envi = solver;
1408   agent->peer = *peer;
1409   agent->step_count = 0;
1410   agent->is_active = GNUNET_NO;
1411   agent->bw_in = 0;
1412   agent->bw_out = 0;
1413   agent->suggestion_issue = GNUNET_NO;
1414   agent->n = RIL_ACTION_TYPE_NUM;
1415   agent->m = (solver->networks_count * RIL_FEATURES_NETWORK_COUNT) + GNUNET_ATS_PreferenceCount;
1416   agent->W = (double **) GNUNET_malloc (sizeof (double *) * agent->n);
1417   for (i = 0; i < agent->n; i++)
1418   {
1419     agent->W[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1420   }
1421   agent_w_start(agent);
1422   agent->a_old = RIL_ACTION_INVALID;
1423   agent->s_old = envi_get_state (solver, agent);
1424   agent->e = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1425   agent_modify_eligibility (agent, RIL_E_ZERO);
1426
1427   GNUNET_CONTAINER_DLL_insert_tail(solver->agents_head, solver->agents_tail, agent);
1428
1429   return agent;
1430 }
1431
1432 /**
1433  * Deallocate agent
1434  *
1435  * @param solver the solver handle
1436  * @param agent the agent to retire
1437  */
1438 static void
1439 agent_die (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
1440 {
1441   int i;
1442
1443   for (i = 0; i < agent->n; i++)
1444   {
1445     GNUNET_free(agent->W[i]);
1446   }
1447   GNUNET_free(agent->W);
1448   GNUNET_free(agent->e);
1449   GNUNET_free(agent->s_old);
1450   GNUNET_free(agent);
1451 }
1452
1453 /**
1454  * Returns the agent for a peer
1455  *
1456  * @param solver the solver handle
1457  * @param peer the identity of the peer
1458  * @param create whether or not to create an agent, if none is allocated yet
1459  * @return the agent
1460  */
1461 static struct RIL_Peer_Agent *
1462 ril_get_agent (struct GAS_RIL_Handle *solver, const struct GNUNET_PeerIdentity *peer, int create)
1463 {
1464   struct RIL_Peer_Agent *cur;
1465
1466   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1467   {
1468     if (0 == memcmp (peer, &cur->peer, sizeof(struct GNUNET_PeerIdentity)))
1469     {
1470       return cur;
1471     }
1472   }
1473
1474   if (create)
1475   {
1476     return agent_init (solver, peer);
1477   }
1478   return NULL ;
1479 }
1480
1481 /**
1482  * Lookup network struct by type
1483  *
1484  * @param s the solver handle
1485  * @param type the network type
1486  * @return the network struct
1487  */
1488 static struct RIL_Network *
1489 ril_get_network (struct GAS_RIL_Handle *s, uint32_t type)
1490 {
1491   int i;
1492
1493   for (i = 0; i < s->networks_count; i++)
1494   {
1495     if (s->network_entries[i].type == type)
1496     {
1497       return &s->network_entries[i];
1498     }
1499   }
1500   return NULL ;
1501 }
1502
1503 /**
1504  * Determine whether at least the minimum bandwidth is set for the network. Otherwise the network is
1505  * considered inactive and not used. Addresses in an inactive network are ignored.
1506  *
1507  * @param solver solver handle
1508  * @param network the network type
1509  * @return whether or not the network is considered active
1510  */
1511 static int
1512 ril_network_is_active (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
1513 {
1514   struct RIL_Network *net;
1515   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1516
1517   net = ril_get_network (solver, network);
1518   if (net->bw_out_available < min_bw)
1519     return GNUNET_NO;
1520   return GNUNET_YES;
1521 }
1522
1523 /**
1524  * Cuts a slice out of a vector of elements. This is used to decrease the size of the matrix storing
1525  * the reward function approximation. It copies the memory, which is not cut, to the new vector,
1526  * frees the memory of the old vector, and redirects the pointer to the new one.
1527  *
1528  * @param old pointer to the pointer to the first element of the vector
1529  * @param element_size byte size of the vector elements
1530  * @param hole_start the first element to cut out
1531  * @param hole_length the number of elements to cut out
1532  * @param old_length the length of the old vector
1533  */
1534 static void
1535 ril_cut_from_vector (void **old,
1536     size_t element_size,
1537     unsigned int hole_start,
1538     unsigned int hole_length,
1539     unsigned int old_length)
1540 {
1541   char *tmpptr;
1542   char *oldptr = (char *) *old;
1543   size_t size;
1544   unsigned int bytes_before;
1545   unsigned int bytes_hole;
1546   unsigned int bytes_after;
1547
1548   GNUNET_assert(old_length > hole_length);
1549   GNUNET_assert(old_length >= (hole_start + hole_length));
1550
1551   size = element_size * (old_length - hole_length);
1552
1553   bytes_before = element_size * hole_start;
1554   bytes_hole = element_size * hole_length;
1555   bytes_after = element_size * (old_length - hole_start - hole_length);
1556
1557   if (0 == size)
1558   {
1559     tmpptr = NULL;
1560   }
1561   else
1562   {
1563     tmpptr = GNUNET_malloc (size);
1564     memcpy (tmpptr, oldptr, bytes_before);
1565     memcpy (tmpptr + bytes_before, oldptr + (bytes_before + bytes_hole), bytes_after);
1566   }
1567   if (NULL != *old)
1568   {
1569     GNUNET_free(*old);
1570   }
1571   *old = (void *) tmpptr;
1572 }
1573
1574 /*
1575  *  Solver API functions
1576  *  ---------------------------
1577  */
1578
1579 /**
1580  * Change relative preference for quality in solver
1581  *
1582  * @param solver the solver handle
1583  * @param peer the peer to change the preference for
1584  * @param kind the kind to change the preference
1585  * @param pref_rel the normalized preference value for this kind over all clients
1586  */
1587 void
1588 GAS_ril_address_change_preference (void *solver,
1589     const struct GNUNET_PeerIdentity *peer,
1590     enum GNUNET_ATS_PreferenceKind kind,
1591     double pref_rel)
1592 {
1593   LOG(GNUNET_ERROR_TYPE_DEBUG,
1594       "API_address_change_preference() Preference '%s' for peer '%s' changed to %.2f \n",
1595       GNUNET_ATS_print_preference_type (kind), GNUNET_i2s (peer), pref_rel);
1596
1597   ril_step (solver);
1598 }
1599
1600 /**
1601  * Entry point for the plugin
1602  *
1603  * @param cls pointer to the 'struct GNUNET_ATS_PluginEnvironment'
1604  */
1605 void *
1606 libgnunet_plugin_ats_ril_init (void *cls)
1607 {
1608   struct GNUNET_ATS_PluginEnvironment *env = cls;
1609   struct GAS_RIL_Handle *solver = GNUNET_new (struct GAS_RIL_Handle);
1610   struct RIL_Network * cur;
1611   int c;
1612   char *string;
1613
1614   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_init() Initializing RIL solver\n");
1615
1616   GNUNET_assert(NULL != env);
1617   GNUNET_assert(NULL != env->cfg);
1618   GNUNET_assert(NULL != env->stats);
1619   GNUNET_assert(NULL != env->bandwidth_changed_cb);
1620   GNUNET_assert(NULL != env->get_preferences);
1621   GNUNET_assert(NULL != env->get_property);
1622
1623   if (GNUNET_OK
1624       != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MIN",
1625           &solver->parameters.step_time_min))
1626   {
1627     solver->parameters.step_time_min = RIL_DEFAULT_STEP_TIME_MIN;
1628   }
1629   if (GNUNET_OK
1630       != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MAX",
1631           &solver->parameters.step_time_max))
1632   {
1633     solver->parameters.step_time_max = RIL_DEFAULT_STEP_TIME_MAX;
1634   }
1635   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_ALGORITHM", &string))
1636   {
1637     solver->parameters.algorithm = !strcmp (string, "SARSA") ? RIL_ALGO_SARSA : RIL_ALGO_Q;
1638     GNUNET_free (string);
1639   }
1640   else
1641   {
1642     solver->parameters.algorithm = RIL_DEFAULT_ALGORITHM;
1643   }
1644   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_DISCOUNT_BETA", &string))
1645   {
1646     solver->parameters.beta = strtod (string, NULL);
1647     GNUNET_free (string);
1648   }
1649   else
1650   {
1651     solver->parameters.beta = RIL_DEFAULT_DISCOUNT_BETA;
1652   }
1653   if (GNUNET_OK
1654       == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_GRADIENT_STEP_SIZE", &string))
1655   {
1656     solver->parameters.alpha = strtod (string, NULL);
1657     GNUNET_free (string);
1658   }
1659   else
1660   {
1661     solver->parameters.alpha = RIL_DEFAULT_GRADIENT_STEP_SIZE;
1662   }
1663   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_TRACE_DECAY", &string))
1664   {
1665     solver->parameters.lambda = strtod (string, NULL);
1666     GNUNET_free (string);
1667   }
1668   else
1669   {
1670     solver->parameters.lambda = RIL_DEFAULT_TRACE_DECAY;
1671   }
1672   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_EXPLORE_RATIO", &string))
1673   {
1674     solver->parameters.explore_ratio = strtod (string, NULL);
1675     GNUNET_free (string);
1676   }
1677   else
1678   {
1679     solver->parameters.explore_ratio = RIL_DEFAULT_EXPLORE_RATIO;
1680   }
1681
1682   env->sf.s_add = &GAS_ril_address_add;
1683   env->sf.s_address_update_property = &GAS_ril_address_property_changed;
1684   env->sf.s_address_update_session = &GAS_ril_address_session_changed;
1685   env->sf.s_address_update_inuse = &GAS_ril_address_inuse_changed;
1686   env->sf.s_address_update_network = &GAS_ril_address_change_network;
1687   env->sf.s_get = &GAS_ril_get_preferred_address;
1688   env->sf.s_get_stop = &GAS_ril_stop_get_preferred_address;
1689   env->sf.s_pref = &GAS_ril_address_change_preference;
1690   env->sf.s_feedback = &GAS_ril_address_preference_feedback;
1691   env->sf.s_del = &GAS_ril_address_delete;
1692   env->sf.s_bulk_start = &GAS_ril_bulk_start;
1693   env->sf.s_bulk_stop = &GAS_ril_bulk_stop;
1694
1695   solver->plugin_envi = env;
1696   solver->networks_count = env->network_count;
1697   solver->network_entries = GNUNET_malloc (env->network_count * sizeof (struct RIL_Network));
1698   solver->step_count = 0;
1699   solver->state_networks = GNUNET_malloc (solver->networks_count * RIL_FEATURES_NETWORK_COUNT * sizeof (double));
1700
1701   for (c = 0; c < env->network_count; c++)
1702   {
1703     cur = &solver->network_entries[c];
1704     cur->type = env->networks[c];
1705     cur->bw_in_available = env->in_quota[c];
1706     cur->bw_out_available = env->out_quota[c];
1707   }
1708
1709   solver->step_next_task_id = GNUNET_SCHEDULER_add_delayed (
1710       GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_get_millisecond_ (), 1000),
1711       &ril_step_scheduler_task, solver);
1712   solver->task_pending = GNUNET_YES;
1713
1714   return solver;
1715 }
1716
1717 /**
1718  * Exit point for the plugin
1719  *
1720  * @param cls the solver handle
1721  */
1722 void *
1723 libgnunet_plugin_ats_ril_done (void *cls)
1724 {
1725   struct GAS_RIL_Handle *s = cls;
1726   struct RIL_Peer_Agent *cur_agent;
1727   struct RIL_Peer_Agent *next_agent;
1728
1729   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_done() Shutting down RIL solver\n");
1730
1731   cur_agent = s->agents_head;
1732   while (NULL != cur_agent)
1733   {
1734     next_agent = cur_agent->next;
1735     GNUNET_CONTAINER_DLL_remove(s->agents_head, s->agents_tail, cur_agent);
1736     agent_die (s, cur_agent);
1737     cur_agent = next_agent;
1738   }
1739
1740   if (s->task_pending)
1741   {
1742     GNUNET_SCHEDULER_cancel (s->step_next_task_id);
1743   }
1744   GNUNET_free(s->network_entries);
1745   GNUNET_free(s->state_networks);
1746   GNUNET_free(s);
1747
1748   return NULL ;
1749 }
1750
1751 /**
1752  * Add a new address for a peer to the solver
1753  *
1754  * The address is already contained in the addresses hashmap!
1755  *
1756  * @param solver the solver Handle
1757  * @param address the address to add
1758  * @param network network type of this address
1759  */
1760 void
1761 GAS_ril_address_add (void *solver, struct ATS_Address *address, uint32_t network)
1762 {
1763   struct GAS_RIL_Handle *s = solver;
1764   struct RIL_Peer_Agent *agent;
1765   struct RIL_Address_Wrapped *address_wrapped;
1766   struct RIL_Network *net;
1767   unsigned int m_new;
1768   unsigned int m_old;
1769   unsigned int n_new;
1770   unsigned int n_old;
1771   int i;
1772   unsigned int zero;
1773   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1774
1775   LOG (GNUNET_ERROR_TYPE_DEBUG, "API_address_add()\n");
1776
1777   net = ril_get_network (s, network);
1778   address->solver_information = net;
1779
1780   if (!ril_network_is_active (s, network))
1781   {
1782     LOG(GNUNET_ERROR_TYPE_DEBUG,
1783         "API_address_add() Did not add %s address %s for peer '%s', network does not have enough bandwidth\n",
1784         address->plugin, address->addr, GNUNET_i2s (&address->peer));
1785     return;
1786   }
1787
1788   agent = ril_get_agent (s, &address->peer, GNUNET_YES);
1789
1790   //add address
1791   address_wrapped = GNUNET_malloc (sizeof (struct RIL_Address_Wrapped));
1792   address_wrapped->address_naked = address;
1793   GNUNET_CONTAINER_DLL_insert_tail(agent->addresses_head, agent->addresses_tail, address_wrapped);
1794
1795   //increase size of W
1796   m_new = agent->m + RIL_FEATURES_ADDRESS_COUNT;
1797   m_old = agent->m;
1798   n_new = agent->n + 1;
1799   n_old = agent->n;
1800
1801   GNUNET_array_grow(agent->W, agent->n, n_new);
1802   for (i = 0; i < n_new; i++)
1803   {
1804     if (i < n_old)
1805     {
1806       agent->m = m_old;
1807       GNUNET_array_grow(agent->W[i], agent->m, m_new);
1808     }
1809     else
1810     {
1811       zero = 0;
1812       GNUNET_array_grow(agent->W[i], zero, m_new);
1813     }
1814   }
1815
1816   //increase size of old state vector
1817   agent->m = m_old;
1818   GNUNET_array_grow(agent->s_old, agent->m, m_new);
1819
1820   agent->m = m_old;
1821   GNUNET_array_grow(agent->e, agent->m, m_new);
1822
1823   if (NULL == agent->address_inuse)
1824   {
1825     envi_set_active_suggestion (s, agent, address, min_bw, min_bw, GNUNET_NO);
1826   }
1827
1828   ril_step (s);
1829
1830   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_add() Added %s %s address %s for peer '%s'\n",
1831       address->active ? "active" : "inactive", address->plugin, address->addr,
1832       GNUNET_i2s (&address->peer));
1833 }
1834
1835 /**
1836  * Delete an address in the solver
1837  *
1838  * The address is not contained in the address hashmap anymore!
1839  *
1840  * @param solver the solver handle
1841  * @param address the address to remove
1842  * @param session_only delete only session not whole address
1843  */
1844 void
1845 GAS_ril_address_delete (void *solver, struct ATS_Address *address, int session_only)
1846 {
1847   struct GAS_RIL_Handle *s = solver;
1848   struct RIL_Peer_Agent *agent;
1849   struct RIL_Address_Wrapped *address_wrapped;
1850   int address_was_used = address->active;
1851   int address_index;
1852   unsigned int m_new;
1853   unsigned int n_new;
1854   int i;
1855   struct RIL_Network *net;
1856   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1857
1858   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_delete() Delete %s%s %s address %s for peer '%s'\n",
1859       session_only ? "session for " : "", address->active ? "active" : "inactive", address->plugin,
1860       address->addr, GNUNET_i2s (&address->peer));
1861
1862   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
1863   if (NULL == agent)
1864   {
1865     net = address->solver_information;
1866     GNUNET_assert(!ril_network_is_active (s, net->type));
1867     LOG(GNUNET_ERROR_TYPE_DEBUG,
1868         "No agent allocated for peer yet, since address was in inactive network\n");
1869     return;
1870   }
1871
1872   address_index = agent_address_get_index (agent, address);
1873   address_wrapped = agent_address_get (agent, address);
1874
1875   if (NULL == address_wrapped)
1876   {
1877     net = address->solver_information;
1878     GNUNET_assert(!ril_network_is_active (s, net->type));
1879     LOG(GNUNET_ERROR_TYPE_DEBUG,
1880         "Address not considered by agent, address was in inactive network\n");
1881     return;
1882   }
1883
1884   GNUNET_CONTAINER_DLL_remove(agent->addresses_head, agent->addresses_tail, address_wrapped);
1885   GNUNET_free(address_wrapped);
1886
1887   //decrease W
1888   m_new = agent->m - RIL_FEATURES_ADDRESS_COUNT;
1889   n_new = agent->n - 1;
1890
1891   for (i = 0; i < agent->n; i++)
1892   {
1893     ril_cut_from_vector ((void **) &agent->W[i], sizeof(double),
1894         ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1895             + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1896   }
1897   GNUNET_free(agent->W[RIL_ACTION_TYPE_NUM + address_index]);
1898   ril_cut_from_vector ((void **) &agent->W, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index,
1899       1, agent->n);
1900   //correct last action
1901   if (agent->a_old > (RIL_ACTION_TYPE_NUM + address_index))
1902   {
1903     agent->a_old -= 1;
1904   }
1905   else if (agent->a_old == (RIL_ACTION_TYPE_NUM + address_index))
1906   {
1907     agent->a_old = RIL_ACTION_INVALID;
1908   }
1909   //decrease old state vector and eligibility vector
1910   ril_cut_from_vector ((void **) &agent->s_old, sizeof(double),
1911       ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1912           + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1913   ril_cut_from_vector ((void **) &agent->e, sizeof(double),
1914       ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1915           + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1916   agent->m = m_new;
1917   agent->n = n_new;
1918
1919   LOG(GNUNET_ERROR_TYPE_DEBUG, "address was used: %s\n", address_was_used ? "yes" : "no");
1920
1921   if (address_was_used)
1922   {
1923     if (NULL != agent->addresses_head) //if peer has an address left, use it
1924     {
1925       LOG(GNUNET_ERROR_TYPE_DEBUG, "address left: %s\n",
1926           agent->addresses_head->address_naked->addr);
1927
1928       envi_set_active_suggestion (s, agent, agent->addresses_head->address_naked, min_bw, min_bw,
1929           GNUNET_NO);
1930     }
1931     else
1932     {
1933       LOG(GNUNET_ERROR_TYPE_DEBUG, "no address left => disconnect\n");
1934
1935       envi_set_active_suggestion (s, agent, NULL, 0, 0, GNUNET_NO);
1936     }
1937   }
1938
1939   LOG(GNUNET_ERROR_TYPE_DEBUG, "Address deleted: %s\n", address->addr);
1940
1941   ril_step (solver);
1942 }
1943
1944 /**
1945  * Update the properties of an address in the solver
1946  *
1947  * @param solver solver handle
1948  * @param address the address
1949  * @param type the ATSI type in HBO
1950  * @param abs_value the absolute value of the property
1951  * @param rel_value the normalized value
1952  */
1953 void
1954 GAS_ril_address_property_changed (void *solver,
1955     struct ATS_Address *address,
1956     uint32_t type,
1957     uint32_t abs_value,
1958     double rel_value)
1959 {
1960   LOG(GNUNET_ERROR_TYPE_DEBUG,
1961       "API_address_property_changed() Property '%s' for peer '%s' address %s changed "
1962           "to %.2f \n", GNUNET_ATS_print_property_type (type), GNUNET_i2s (&address->peer),
1963       address->addr, rel_value);
1964
1965   ril_step (solver);
1966 }
1967
1968 /**
1969  * Update the session of an address in the solver
1970  *
1971  * NOTE: values in addresses are already updated
1972  *
1973  * @param solver solver handle
1974  * @param address the address
1975  * @param cur_session the current session
1976  * @param new_session the new session
1977  */
1978 void
1979 GAS_ril_address_session_changed (void *solver,
1980     struct ATS_Address *address,
1981     uint32_t cur_session,
1982     uint32_t new_session)
1983 {
1984   /*
1985    * TODO? Future Work: Potentially add session activity as a feature in state vector
1986    */
1987   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_session_changed()\n");
1988 }
1989
1990 /**
1991  * Notify the solver that an address is (not) actively used by transport
1992  * to communicate with a remote peer
1993  *
1994  * NOTE: values in addresses are already updated
1995  *
1996  * @param solver solver handle
1997  * @param address the address
1998  * @param in_use usage state
1999  */
2000 void
2001 GAS_ril_address_inuse_changed (void *solver, struct ATS_Address *address, int in_use)
2002 {
2003   /*
2004    * TODO? Future Work: Potentially add usage variable to state vector
2005    */
2006   LOG(GNUNET_ERROR_TYPE_DEBUG,
2007       "API_address_inuse_changed() Usage for %s address of peer '%s' changed to %s\n",
2008       address->plugin, GNUNET_i2s (&address->peer), (GNUNET_YES == in_use) ? "USED" : "UNUSED");
2009 }
2010
2011 /**
2012  * Notify solver that the network an address is located in has changed
2013  *
2014  * NOTE: values in addresses are already updated
2015  *
2016  * @param solver solver handle
2017  * @param address the address
2018  * @param current_network the current network
2019  * @param new_network the new network
2020  */
2021 void
2022 GAS_ril_address_change_network (void *solver,
2023     struct ATS_Address *address,
2024     uint32_t current_network,
2025     uint32_t new_network)
2026 {
2027   struct GAS_RIL_Handle *s = solver;
2028   struct RIL_Peer_Agent *agent;
2029
2030   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_change_network() Network type changed, moving "
2031       "%s address of peer %s from '%s' to '%s'\n",
2032       (GNUNET_YES == address->active) ? "active" : "inactive", GNUNET_i2s (&address->peer),
2033       GNUNET_ATS_print_network_type (current_network), GNUNET_ATS_print_network_type (new_network));
2034
2035   if (address->active && !ril_network_is_active (solver, new_network))
2036   {
2037     GAS_ril_address_delete (solver, address, GNUNET_NO);
2038     return;
2039   }
2040
2041   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
2042   if (NULL == agent)
2043   {
2044     GNUNET_assert(!ril_network_is_active (solver, current_network));
2045
2046     GAS_ril_address_add (s, address, new_network);
2047     return;
2048   }
2049
2050   address->solver_information = ril_get_network(solver, new_network);
2051 }
2052
2053 /**
2054  * Give feedback about the current assignment
2055  *
2056  * @param solver the solver handle
2057  * @param application the application
2058  * @param peer the peer to change the preference for
2059  * @param scope the time interval for this feedback: [now - scope .. now]
2060  * @param kind the kind to change the preference
2061  * @param score the score
2062  */
2063 void
2064 GAS_ril_address_preference_feedback (void *solver,
2065     void *application,
2066     const struct GNUNET_PeerIdentity *peer,
2067     const struct GNUNET_TIME_Relative scope,
2068     enum GNUNET_ATS_PreferenceKind kind,
2069     double score)
2070 {
2071   LOG(GNUNET_ERROR_TYPE_DEBUG,
2072       "API_address_preference_feedback() Peer '%s' got a feedback of %+.3f from application %s for "
2073           "preference %s for %d seconds\n", GNUNET_i2s (peer), "UNKNOWN",
2074       GNUNET_ATS_print_preference_type (kind), scope.rel_value_us / 1000000);
2075 }
2076
2077 /**
2078  * Start a bulk operation
2079  *
2080  * @param solver the solver
2081  */
2082 void
2083 GAS_ril_bulk_start (void *solver)
2084 {
2085   struct GAS_RIL_Handle *s = solver;
2086
2087   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_bulk_start() lock: %d\n", s->bulk_lock+1);
2088
2089   s->bulk_lock++;
2090 }
2091
2092 /**
2093  * Bulk operation done
2094  *
2095  * @param solver the solver handle
2096  */
2097 void
2098 GAS_ril_bulk_stop (void *solver)
2099 {
2100   struct GAS_RIL_Handle *s = solver;
2101
2102   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_bulk_stop() lock: %d\n", s->bulk_lock-1);
2103
2104   if (s->bulk_lock < 1)
2105   {
2106     GNUNET_break(0);
2107     return;
2108   }
2109   s->bulk_lock--;
2110
2111   if (0 < s->bulk_changes)
2112   {
2113     ril_step (solver);
2114     s->bulk_changes = 0;
2115   }
2116 }
2117
2118 /**
2119  * Tell solver to notify ATS if the address to use changes for a specific
2120  * peer using the bandwidth changed callback
2121  *
2122  * The solver must only notify about changes for peers with pending address
2123  * requests!
2124  *
2125  * @param solver the solver handle
2126  * @param peer the identity of the peer
2127  */
2128 const struct ATS_Address *
2129 GAS_ril_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
2130 {
2131   /*
2132    * activate agent, return currently chosen address
2133    */
2134   struct GAS_RIL_Handle *s = solver;
2135   struct RIL_Peer_Agent *agent;
2136
2137   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_get_preferred_address()\n");
2138
2139   agent = ril_get_agent (s, peer, GNUNET_YES);
2140
2141   agent->is_active = GNUNET_YES;
2142
2143   envi_set_active_suggestion (s, agent, agent->address_inuse, agent->bw_in, agent->bw_out,
2144       GNUNET_YES);
2145
2146   if (agent->address_inuse)
2147   {
2148     LOG(GNUNET_ERROR_TYPE_DEBUG,
2149         "API_get_preferred_address() Activated agent for peer '%s' with %s address %s\n",
2150         GNUNET_i2s (peer), agent->address_inuse->plugin, agent->address_inuse->addr);
2151   }
2152   else
2153   {
2154     LOG(GNUNET_ERROR_TYPE_DEBUG,
2155         "API_get_preferred_address() Activated agent for peer '%s', but no address available\n",
2156         GNUNET_i2s (peer));
2157   }
2158
2159   return agent->address_inuse;
2160 }
2161
2162 /**
2163  * Tell solver stop notifying ATS about changes for this peers
2164  *
2165  * The solver must only notify about changes for peers with pending address
2166  * requests!
2167  *
2168  * @param solver the solver handle
2169  * @param peer the peer
2170  */
2171 void
2172 GAS_ril_stop_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
2173 {
2174   struct GAS_RIL_Handle *s = solver;
2175   struct RIL_Peer_Agent *agent;
2176
2177   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_stop_get_preferred_address()");
2178
2179   agent = ril_get_agent (s, peer, GNUNET_NO);
2180
2181   if (NULL == agent)
2182   {
2183     GNUNET_break(0);
2184     return;
2185   }
2186   if (GNUNET_NO == agent->is_active)
2187   {
2188     GNUNET_break(0);
2189     return;
2190   }
2191
2192   agent->is_active = GNUNET_NO;
2193
2194   envi_set_active_suggestion (s, agent, agent->address_inuse, agent->bw_in, agent->bw_out,
2195       GNUNET_YES);
2196
2197   ril_step (s);
2198
2199   LOG(GNUNET_ERROR_TYPE_DEBUG,
2200       "API_stop_get_preferred_address() Paused agent for peer '%s' with %s address\n",
2201       GNUNET_i2s (peer), agent->address_inuse->plugin);
2202 }
2203
2204 /* end of libgnunet_plugin_ats_ril.c */