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