- variables renamed
[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 #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
681   for (i = 0; i < solver->networks_count; i++)
682   {
683     net = solver->network_entries[i];
684     solver->global_state_networks[i * RIL_FEATURES_NETWORK_COUNT + 0] = (double) ril_network_get_assigned(solver, net.type, GNUNET_YES);
685     solver->global_state_networks[i * RIL_FEATURES_NETWORK_COUNT + 1] = (double) net.bw_in_available;
686     solver->global_state_networks[i * RIL_FEATURES_NETWORK_COUNT + 2] = (double) ril_network_get_assigned(solver, net.type, GNUNET_NO);
687     solver->global_state_networks[i * RIL_FEATURES_NETWORK_COUNT + 3] = (double) net.bw_out_available;
688   }
689 }
690
691 /**
692  * Allocates a state vector and fills it with the features present
693  * @param solver the solver handle
694  * @param agent the agent handle
695  * @return pointer to the state vector
696  */
697 static double *
698 envi_get_state (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
699 {
700   int i;
701   int k;
702   double *state = GNUNET_malloc (sizeof (double) * agent->m);
703   struct RIL_Address_Wrapped *cur_address;
704   const double *preferences;
705   const double *properties;
706
707   //copy global networks state
708   for (i = 0; i < solver->networks_count; i++)
709   {
710     state[i * RIL_FEATURES_NETWORK_COUNT + 0] = solver->global_state_networks[i * RIL_FEATURES_NETWORK_COUNT + 0];
711     state[i * RIL_FEATURES_NETWORK_COUNT + 1] = solver->global_state_networks[i * RIL_FEATURES_NETWORK_COUNT + 1];
712     state[i * RIL_FEATURES_NETWORK_COUNT + 2] = solver->global_state_networks[i * RIL_FEATURES_NETWORK_COUNT + 2];
713     state[i * RIL_FEATURES_NETWORK_COUNT + 3] = solver->global_state_networks[i * RIL_FEATURES_NETWORK_COUNT + 3];
714   }
715
716   //get peer features
717   i = i * RIL_FEATURES_NETWORK_COUNT;
718   preferences = solver->plugin_envi->get_preferences (solver->plugin_envi->get_preference_cls,
719         &agent->peer);
720   for (k = 0; k < GNUNET_ATS_PreferenceCount; k++)
721   {
722     state[i++] = preferences[k];
723   }
724
725   //get address specific features
726   for (cur_address = agent->addresses_head; NULL != cur_address; cur_address = cur_address->next)
727   {
728     //when changing the number of address specific state features, change RIL_FEATURES_ADDRESS_COUNT macro
729     state[i++] = cur_address->address_naked->active;
730     state[i++] = cur_address->address_naked->active ? agent->bw_in : 0;
731     state[i++] = cur_address->address_naked->active ? agent->bw_out : 0;
732     properties = solver->plugin_envi->get_property (solver->plugin_envi->get_property_cls,
733         cur_address->address_naked);
734     for (k = 0; k < GNUNET_ATS_QualityPropertiesCount; k++)
735     {
736       state[i++] = properties[k];
737     }
738   }
739
740   return state;
741 }
742
743 /**
744  * For all networks a peer has an address in, this gets the maximum bandwidth which could
745  * theoretically be available in one of the networks. This is used for bandwidth normalization.
746  *
747  * @param agent the agent handle
748  * @param direction_in whether the inbound bandwidth should be considered. Returns the maximum outbound bandwidth if GNUNET_NO
749  */
750 static long long unsigned
751 ril_get_max_bw (struct RIL_Peer_Agent *agent, int direction_in)
752 {
753   /*
754    * get the maximum bandwidth possible for a peer, e.g. among all addresses which addresses'
755    * network could provide the maximum bandwidth if all that bandwidth was used on that one peer.
756    */
757   int max = 0;
758   struct RIL_Address_Wrapped *cur;
759   struct RIL_Network *net;
760
761   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
762   {
763     net = cur->address_naked->solver_information;
764     if (direction_in)
765     {
766       if (net->bw_in_available > max)
767       {
768         max = net->bw_in_available;
769       }
770     }
771     else
772     {
773       if (net->bw_out_available > max)
774       {
775         max = net->bw_out_available;
776       }
777     }
778   }
779   return max;
780 }
781
782 /**
783  * Get the index of the quality-property in question
784  *
785  * @param type the quality property type
786  * @return the index
787  */
788 static int
789 ril_find_property_index (uint32_t type)
790 {
791   int existing_types[] = GNUNET_ATS_QualityProperties;
792   int c;
793   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
794     if (existing_types[c] == type)
795       return c;
796   return GNUNET_SYSERR;
797 }
798
799 static int
800 ril_get_atsi (struct ATS_Address *address, uint32_t type)
801 {
802   int c1;
803   GNUNET_assert(NULL != address);
804
805   if ((NULL == address->atsi) || (0 == address->atsi_count))
806     return 0;
807
808   for (c1 = 0; c1 < address->atsi_count; c1++)
809   {
810     if (ntohl (address->atsi[c1].type) == type)
811       return ntohl (address->atsi[c1].value);
812   }
813   return 0;
814 }
815
816 static double
817 envi_reward_global (struct GAS_RIL_Handle *solver)
818 {
819   int i;
820   struct RIL_Network net;
821   unsigned int sum_in_available = 0;
822   unsigned int sum_out_available = 0;
823   unsigned int sum_in_assigned = 0;
824   unsigned int sum_out_assigned = 0;
825   double ratio_in;
826   double ratio_out;
827
828   for (i = 0; i < solver->networks_count; i++)
829   {
830     net = solver->network_entries[i];
831     sum_in_available += net.bw_in_available;
832     sum_in_assigned += ril_network_get_assigned(solver, net.type, GNUNET_YES);
833     sum_out_available += net.bw_out_available;
834     sum_out_assigned += ril_network_get_assigned(solver, net.type, GNUNET_NO);
835   }
836
837   ratio_in = ((double) sum_in_assigned) / ((double) sum_in_available);
838   ratio_out = ((double) sum_out_assigned) / ((double) sum_out_available);
839
840   // global reward in [1,2]
841   return ((ratio_in + ratio_out) / 2) + 1;
842 }
843
844 static double
845 envi_reward_local (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
846 {
847   const double *preferences;
848   const double *properties;
849   int prop_index;
850   double pref_match = 0;
851   double bw_norm;
852   double dl_norm;
853
854   preferences = solver->plugin_envi->get_preferences (solver->plugin_envi->get_preference_cls,
855       &agent->peer);
856   properties = solver->plugin_envi->get_property (solver->plugin_envi->get_property_cls,
857       agent->address_inuse);
858
859   // delay in [0,1]
860   prop_index = ril_find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
861   dl_norm = 2 - properties[prop_index]; //invert property as we want to maximize for lower latencies
862
863   // utilization in [0,1]
864   bw_norm = ((ril_get_atsi (agent->address_inuse, GNUNET_ATS_UTILIZATION_IN)
865       / ril_get_max_bw (agent, GNUNET_YES))
866       + (ril_get_atsi (agent->address_inuse, GNUNET_ATS_UTILIZATION_OUT)
867           / ril_get_max_bw (agent, GNUNET_NO))) / 2;
868
869   // preference matching in [0,4]
870   pref_match += (preferences[GNUNET_ATS_PREFERENCE_LATENCY] * dl_norm);
871   pref_match += (preferences[GNUNET_ATS_PREFERENCE_BANDWIDTH] * bw_norm);
872
873   // local reward in [1,2]
874   return (pref_match / 4) +1;
875 }
876
877 /**
878  * Gets the reward for the last performed step, which is calculated in equal
879  * parts from the local (the peer specific) and the global (for all peers
880  * identical) reward.
881  *
882  * @param solver the solver handle
883  * @param agent the agent handle
884  * @return the reward
885  */
886 static double
887 envi_get_reward (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
888 {
889   struct RIL_Network *net;
890   double reward = 0;
891
892   //punish overutilization
893   net = agent->address_inuse->solver_information;
894   if ((ril_network_get_assigned(solver, net->type, GNUNET_YES) > net->bw_in_available)
895       || (ril_network_get_assigned(solver, net->type, GNUNET_NO) > net->bw_out_available))
896   {
897     return 0;
898   }
899
900   reward += envi_reward_global (solver) * (solver->parameters.reward_global_share);
901   reward += envi_reward_local (solver, agent) * (1 - solver->parameters.reward_global_share);
902
903   return reward;
904 }
905
906 /**
907  * Doubles the bandwidth for the active address
908  *
909  * @param solver solver handle
910  * @param agent agent handle
911  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise the outbound bandwidth
912  */
913 static void
914 envi_action_bw_double (struct GAS_RIL_Handle *solver,
915     struct RIL_Peer_Agent *agent,
916     int direction_in)
917 {
918   unsigned long long new_bw;
919
920   if (direction_in)
921   {
922     new_bw = agent->bw_in * 2;
923     if (new_bw < agent->bw_in)
924       new_bw = ULLONG_MAX;
925     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw,
926         agent->bw_out, GNUNET_NO);
927   }
928   else
929   {
930     new_bw = agent->bw_out * 2;
931     if (new_bw < agent->bw_out)
932       new_bw = ULLONG_MAX;
933     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
934         new_bw, GNUNET_NO);
935   }
936 }
937
938 /**
939  * Cuts the bandwidth for the active address in half. The least amount of bandwidth suggested, is
940  * the minimum bandwidth for a peer, in order to not invoke a disconnect.
941  *
942  * @param solver solver handle
943  * @param agent agent handle
944  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
945  * bandwidth
946  */
947 static void
948 envi_action_bw_halven (struct GAS_RIL_Handle *solver,
949     struct RIL_Peer_Agent *agent,
950     int direction_in)
951 {
952   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
953   unsigned long long new_bw;
954
955   if (direction_in)
956   {
957     new_bw = agent->bw_in / 2;
958     if (new_bw < min_bw || new_bw > agent->bw_in)
959       new_bw = min_bw;
960     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
961         GNUNET_NO);
962   }
963   else
964   {
965     new_bw = agent->bw_out / 2;
966     if (new_bw < min_bw || new_bw > agent->bw_out)
967       new_bw = min_bw;
968     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
969         GNUNET_NO);
970   }
971 }
972
973 /**
974  * Increases the bandwidth by 5 times the minimum bandwidth for the active address.
975  *
976  * @param solver solver handle
977  * @param agent agent handle
978  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
979  * bandwidth
980  */
981 static void
982 envi_action_bw_inc (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
983 {
984   unsigned long long new_bw;
985   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
986
987   if (direction_in)
988   {
989     new_bw = agent->bw_in + (5 * min_bw);
990     if (new_bw < agent->bw_in)
991       new_bw = ULLONG_MAX;
992     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw,
993         agent->bw_out, GNUNET_NO);
994   }
995   else
996   {
997     new_bw = agent->bw_out + (5 * min_bw);
998     if (new_bw < agent->bw_out)
999       new_bw = ULLONG_MAX;
1000     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
1001         new_bw, GNUNET_NO);
1002   }
1003 }
1004
1005 /**
1006  * Decreases the bandwidth by 5 times the minimum bandwidth for the active address. The least amount
1007  * of bandwidth suggested, is the minimum bandwidth for a peer, in order to not invoke a disconnect.
1008  *
1009  * @param solver solver handle
1010  * @param agent agent handle
1011  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
1012  * bandwidth
1013  */
1014 static void
1015 envi_action_bw_dec (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
1016 {
1017   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1018   unsigned long long new_bw;
1019
1020   if (direction_in)
1021   {
1022     new_bw = agent->bw_in - (5 * min_bw);
1023     if (new_bw < min_bw || new_bw > agent->bw_in)
1024       new_bw = min_bw;
1025     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
1026         GNUNET_NO);
1027   }
1028   else
1029   {
1030     new_bw = agent->bw_out - (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, agent->bw_in, new_bw,
1034         GNUNET_NO);
1035   }
1036 }
1037
1038 /**
1039  * Switches to the address given by its index
1040  *
1041  * @param solver solver handle
1042  * @param agent agent handle
1043  * @param address_index index of the address as it is saved in the agent's list, starting with zero
1044  */
1045 static void
1046 envi_action_address_switch (struct GAS_RIL_Handle *solver,
1047     struct RIL_Peer_Agent *agent,
1048     unsigned int address_index)
1049 {
1050   struct RIL_Address_Wrapped *cur;
1051   int i = 0;
1052
1053   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
1054   {
1055     if (i == address_index)
1056     {
1057       envi_set_active_suggestion (solver, agent, cur->address_naked, agent->bw_in, agent->bw_out,
1058           GNUNET_NO);
1059       return;
1060     }
1061
1062     i++;
1063   }
1064
1065   //no address with address_index exists, in this case this action should not be callable
1066   GNUNET_assert(GNUNET_NO);
1067 }
1068
1069 /**
1070  * Puts the action into effect by calling the according function
1071  *
1072  * @param solver the solver handle
1073  * @param agent the action handle
1074  * @param action the action to perform by the solver
1075  */
1076 static void
1077 envi_do_action (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int action)
1078 {
1079   int address_index;
1080
1081   switch (action)
1082   {
1083   case RIL_ACTION_NOTHING:
1084     break;
1085   case RIL_ACTION_BW_IN_DBL:
1086     envi_action_bw_double (solver, agent, GNUNET_YES);
1087     break;
1088   case RIL_ACTION_BW_IN_HLV:
1089     envi_action_bw_halven (solver, agent, GNUNET_YES);
1090     break;
1091   case RIL_ACTION_BW_IN_INC:
1092     envi_action_bw_inc (solver, agent, GNUNET_YES);
1093     break;
1094   case RIL_ACTION_BW_IN_DEC:
1095     envi_action_bw_dec (solver, agent, GNUNET_YES);
1096     break;
1097   case RIL_ACTION_BW_OUT_DBL:
1098     envi_action_bw_double (solver, agent, GNUNET_NO);
1099     break;
1100   case RIL_ACTION_BW_OUT_HLV:
1101     envi_action_bw_halven (solver, agent, GNUNET_NO);
1102     break;
1103   case RIL_ACTION_BW_OUT_INC:
1104     envi_action_bw_inc (solver, agent, GNUNET_NO);
1105     break;
1106   case RIL_ACTION_BW_OUT_DEC:
1107     envi_action_bw_dec (solver, agent, GNUNET_NO);
1108     break;
1109   default:
1110     if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action
1111     {
1112       address_index = action - RIL_ACTION_TYPE_NUM;
1113
1114       GNUNET_assert(address_index >= 0);
1115       GNUNET_assert(
1116           address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked));
1117
1118       envi_action_address_switch (solver, agent, address_index);
1119       break;
1120     }
1121     // error - action does not exist
1122     GNUNET_assert(GNUNET_NO);
1123   }
1124 }
1125
1126 /**
1127  * Performs one step of the Markov Decision Process. Other than in the literature the step starts
1128  * after having done the last action a_old. It observes the new state s_next and the reward
1129  * received. Then the coefficient update is done according to the SARSA or Q-learning method. The
1130  * next action is put into effect.
1131  *
1132  * @param agent the agent performing the step
1133  */
1134 static void
1135 agent_step (struct RIL_Peer_Agent *agent)
1136 {
1137   int a_next = RIL_ACTION_INVALID;
1138   double *s_next;
1139   double reward;
1140
1141   LOG(GNUNET_ERROR_TYPE_DEBUG, "    agent_step() Peer '%s', algorithm %s\n",
1142       GNUNET_i2s (&agent->peer),
1143       agent->envi->parameters.algorithm ? "Q" : "SARSA");
1144
1145   s_next = envi_get_state (agent->envi, agent);
1146   reward = envi_get_reward (agent->envi, agent);
1147
1148   switch (agent->envi->parameters.algorithm)
1149   {
1150   case RIL_ALGO_SARSA:
1151     agent_modify_eligibility (agent, RIL_E_SET);
1152     if (agent_decide_exploration (agent))
1153     {
1154       a_next = agent_get_action_explore (agent, s_next);
1155     }
1156     else
1157     {
1158       a_next = agent_get_action_best (agent, s_next);
1159     }
1160     if (RIL_ACTION_INVALID != agent->a_old)
1161     {
1162       //updates weights with selected action (on-policy), if not first step
1163       agent_update_weights (agent, reward, s_next, a_next);
1164     }
1165     break;
1166
1167   case RIL_ALGO_Q:
1168     a_next = agent_get_action_best (agent, s_next);
1169     if (RIL_ACTION_INVALID != agent->a_old)
1170     {
1171       //updates weights with best action, disregarding actually selected action (off-policy), if not first step
1172       agent_update_weights (agent, reward, s_next, a_next);
1173     }
1174     if (agent_decide_exploration (agent))
1175     {
1176       a_next = agent_get_action_explore (agent, s_next);
1177       agent_modify_eligibility (agent, RIL_E_ZERO);
1178     }
1179     else
1180     {
1181       a_next = agent_get_action_best (agent, s_next);
1182       agent_modify_eligibility (agent, RIL_E_SET);
1183     }
1184     break;
1185   }
1186
1187   GNUNET_assert(RIL_ACTION_INVALID != a_next);
1188
1189   agent_modify_eligibility (agent, RIL_E_ACCUMULATE);
1190
1191   envi_do_action (agent->envi, agent, a_next);
1192
1193   GNUNET_free(agent->s_old);
1194   agent->s_old = s_next;
1195   agent->a_old = a_next;
1196
1197   agent->step_count += 1;
1198 }
1199
1200 static int
1201 ril_step (struct GAS_RIL_Handle *solver);
1202
1203 /**
1204  * Task for the scheduler, which performs one step and lets the solver know that
1205  * no further step is scheduled.
1206  *
1207  * @param cls the solver handle
1208  * @param tc the task context for the scheduler
1209  */
1210 static void
1211 ril_step_scheduler_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1212 {
1213   struct GAS_RIL_Handle *solver = cls;
1214
1215   solver->step_task_pending = GNUNET_NO;
1216   ril_step (solver);
1217 }
1218
1219 static double
1220 ril_get_used_resource_ratio (struct GAS_RIL_Handle *solver)
1221 {
1222   int i;
1223   struct RIL_Network net;
1224   unsigned long long sum_assigned = 0;
1225   unsigned long long sum_available = 0;
1226   double ratio;
1227
1228   for (i = 0; i < solver->networks_count; i++)
1229   {
1230     net = solver->network_entries[i];
1231     if (ril_network_get_assigned(solver, net.type, GNUNET_YES) > 0) //only consider scopes with an active address
1232     {
1233       sum_assigned += ril_network_get_assigned(solver, net.type, GNUNET_YES);
1234       sum_assigned += ril_network_get_assigned(solver, net.type, GNUNET_NO);
1235       sum_available += net.bw_in_available;
1236       sum_available += net.bw_out_available;
1237     }
1238   }
1239   if (sum_available > 0)
1240   {
1241     ratio = ((double) sum_assigned) / ((double) sum_available);
1242   }
1243   else
1244   {
1245     ratio = 0;
1246   }
1247
1248   return ratio > 1 ? 1 : ratio; //overutilization possible, cap at 1
1249 }
1250
1251 /**
1252  * Lookup network struct by type
1253  *
1254  * @param s the solver handle
1255  * @param type the network type
1256  * @return the network struct
1257  */
1258 static struct RIL_Network *
1259 ril_get_network (struct GAS_RIL_Handle *s, uint32_t type)
1260 {
1261   int i;
1262
1263   for (i = 0; i < s->networks_count; i++)
1264   {
1265     if (s->network_entries[i].type == type)
1266     {
1267       return &s->network_entries[i];
1268     }
1269   }
1270   return NULL ;
1271 }
1272
1273 static int
1274 ril_network_is_not_full (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
1275 {
1276   struct RIL_Network *net;
1277   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1278   struct RIL_Peer_Agent *agent;
1279   unsigned long long address_count = 0;
1280
1281   for (agent = solver->agents_head; NULL != agent; agent = agent->next)
1282   {
1283     if (agent->address_inuse && agent->is_active)
1284     {
1285       net = agent->address_inuse->solver_information;
1286       if (net->type == network)
1287       {
1288         address_count++;
1289       }
1290     }
1291   }
1292
1293   net = ril_get_network (solver, network);
1294   return (net->bw_in_available > min_bw * address_count) && (net->bw_out_available > min_bw * address_count);
1295 }
1296
1297 static void
1298 ril_try_unblock_agent (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int silent)
1299 {
1300   struct RIL_Address_Wrapped *addr_wrap;
1301   struct RIL_Network *net;
1302   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1303
1304   for (addr_wrap = agent->addresses_head; NULL != addr_wrap; addr_wrap = addr_wrap->next)
1305   {
1306     net = addr_wrap->address_naked->solver_information;
1307     if (ril_network_is_not_full(solver, net->type))
1308     {
1309       if (NULL == agent->address_inuse)
1310         envi_set_active_suggestion (solver, agent, addr_wrap->address_naked, min_bw, min_bw, silent);
1311       return;
1312     }
1313   }
1314   agent->address_inuse = NULL;
1315 }
1316
1317 /**
1318  * Schedules the next global step in an adaptive way. The more resources are
1319  * left, the earlier the next step is scheduled. This serves the reactivity of
1320  * the solver to changed inputs.
1321  *
1322  * @param solver the solver handle
1323  */
1324 static void
1325 ril_step_schedule_next (struct GAS_RIL_Handle *solver)
1326 {
1327   double used_ratio;
1328   double factor;
1329   double y;
1330   double offset;
1331   struct GNUNET_TIME_Relative time_next;
1332
1333   if (solver->step_task_pending)
1334   {
1335     GNUNET_SCHEDULER_cancel (solver->step_next_task_id);
1336   }
1337
1338   used_ratio = ril_get_used_resource_ratio (solver);
1339
1340   GNUNET_assert(
1341       solver->parameters.step_time_min.rel_value_us
1342           < solver->parameters.step_time_max.rel_value_us);
1343
1344   factor = (double) GNUNET_TIME_relative_subtract (solver->parameters.step_time_max,
1345       solver->parameters.step_time_min).rel_value_us;
1346   offset = (double) solver->parameters.step_time_min.rel_value_us;
1347   y = factor * pow (used_ratio, RIL_INTERVAL_EXPONENT) + offset;
1348
1349   GNUNET_assert(y <= (double ) solver->parameters.step_time_max.rel_value_us);
1350   GNUNET_assert(y >= (double ) solver->parameters.step_time_min.rel_value_us);
1351
1352   time_next = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MICROSECONDS, (unsigned int) y);
1353
1354   solver->step_next_task_id = GNUNET_SCHEDULER_add_delayed (time_next, &ril_step_scheduler_task,
1355       solver);
1356   solver->step_task_pending = GNUNET_YES;
1357 }
1358
1359 /**
1360  * Triggers one step per agent
1361  * @param solver
1362  */
1363 static int
1364 ril_step (struct GAS_RIL_Handle *solver)
1365 {
1366   struct RIL_Peer_Agent *cur;
1367   struct GNUNET_TIME_Absolute time_now;
1368   struct GNUNET_TIME_Relative time_delta;
1369   double tau;
1370
1371   if (GNUNET_YES == solver->bulk_lock)
1372   {
1373     solver->bulk_changes++;
1374     return GNUNET_NO;
1375   }
1376
1377   ril_inform (solver, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS);
1378
1379   LOG(GNUNET_ERROR_TYPE_DEBUG, "    RIL step number %d\n", solver->step_count);
1380
1381   if (0 == solver->step_count)
1382   {
1383     solver->step_time_last = GNUNET_TIME_absolute_get ();
1384   }
1385
1386   //calculate tau, i.e. how many real valued time units have passed, one time unit is one minimum time step
1387   time_now = GNUNET_TIME_absolute_get ();
1388   time_delta = GNUNET_TIME_absolute_get_difference (solver->step_time_last, time_now);
1389   tau = ((double) time_delta.rel_value_us)
1390       / ((double) solver->parameters.step_time_min.rel_value_us);
1391   solver->step_time_last = time_now;
1392
1393   //calculate reward discounts (once per step for all agents)
1394   solver->global_discount_variable = pow (M_E, ((-1.) * ((double) solver->parameters.beta) * tau));
1395   solver->global_discount_integrated = (1 - solver->global_discount_variable)
1396       / ((double) solver->parameters.beta);
1397
1398   //calculate network state vector
1399   envi_state_networks(solver);
1400
1401   //trigger one step per active agent
1402   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1403   {
1404     if (cur->is_active)
1405     {
1406       if (NULL == cur->address_inuse)
1407       {
1408         ril_try_unblock_agent(solver, cur, GNUNET_NO);
1409       }
1410       if (cur->address_inuse)
1411       {
1412         agent_step (cur);
1413       }
1414     }
1415   }
1416
1417   solver->step_count += 1;
1418   ril_step_schedule_next (solver);
1419
1420   ril_inform (solver, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS);
1421
1422   ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, GAS_STAT_SUCCESS);
1423   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1424   {
1425     if (cur->suggestion_issue) {
1426       solver->plugin_envi->bandwidth_changed_cb(solver->plugin_envi->bw_changed_cb_cls, cur->suggestion_address);
1427       cur->suggestion_issue = GNUNET_NO;
1428     }
1429   }
1430   ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, GAS_STAT_SUCCESS);
1431
1432   return GNUNET_YES;
1433 }
1434
1435 static int
1436 ril_count_agents (struct GAS_RIL_Handle *solver)
1437 {
1438   int c = 0;
1439   struct RIL_Peer_Agent *cur_agent;
1440
1441   for (cur_agent = solver->agents_head; NULL != cur_agent; cur_agent = cur_agent->next)
1442   {
1443     c++;
1444   }
1445   return c;
1446 }
1447
1448 static void
1449 agent_w_start (struct RIL_Peer_Agent *agent)
1450 {
1451   int count;
1452   struct RIL_Peer_Agent *other;
1453   int i;
1454   int k;
1455
1456   count = ril_count_agents(agent->envi);
1457
1458   if (0 == count)
1459     return;
1460
1461   for (other = agent->envi->agents_head; NULL != other; other = other->next)
1462   {
1463     for (i = 0; i < agent->n; i++)
1464     {
1465       for (k = 0; k < agent->m; k++)
1466       {
1467         agent->W[i][k] += (other->W[i][k] / (double) count);
1468       }
1469     }
1470   }
1471 }
1472
1473 /**
1474  * Initialize an agent without addresses and its knowledge base
1475  *
1476  * @param s ril solver
1477  * @param peer the one in question
1478  * @return handle to the new agent
1479  */
1480 static struct RIL_Peer_Agent *
1481 agent_init (void *s, const struct GNUNET_PeerIdentity *peer)
1482 {
1483   int i;
1484   struct GAS_RIL_Handle * solver = s;
1485   struct RIL_Peer_Agent * agent = GNUNET_malloc (sizeof (struct RIL_Peer_Agent));
1486
1487   agent->envi = solver;
1488   agent->peer = *peer;
1489   agent->step_count = 0;
1490   agent->is_active = GNUNET_NO;
1491   agent->bw_in = 0;
1492   agent->bw_out = 0;
1493   agent->suggestion_issue = GNUNET_NO;
1494   agent->n = RIL_ACTION_TYPE_NUM;
1495   agent->m = (solver->networks_count * RIL_FEATURES_NETWORK_COUNT) + GNUNET_ATS_PreferenceCount;
1496   agent->W = (double **) GNUNET_malloc (sizeof (double *) * agent->n);
1497   for (i = 0; i < agent->n; i++)
1498   {
1499     agent->W[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1500   }
1501   agent_w_start(agent);
1502   agent->a_old = RIL_ACTION_INVALID;
1503   agent->s_old = envi_get_state (solver, agent);
1504   agent->e = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1505   agent_modify_eligibility (agent, RIL_E_ZERO);
1506
1507   return agent;
1508 }
1509
1510 /**
1511  * Deallocate agent
1512  *
1513  * @param solver the solver handle
1514  * @param agent the agent to retire
1515  */
1516 static void
1517 agent_die (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
1518 {
1519   int i;
1520
1521   for (i = 0; i < agent->n; i++)
1522   {
1523     GNUNET_free(agent->W[i]);
1524   }
1525   GNUNET_free(agent->W);
1526   GNUNET_free(agent->e);
1527   GNUNET_free(agent->s_old);
1528   GNUNET_free(agent);
1529 }
1530
1531 /**
1532  * Returns the agent for a peer
1533  *
1534  * @param solver the solver handle
1535  * @param peer the identity of the peer
1536  * @param create whether or not to create an agent, if none is allocated yet
1537  * @return the agent
1538  */
1539 static struct RIL_Peer_Agent *
1540 ril_get_agent (struct GAS_RIL_Handle *solver, const struct GNUNET_PeerIdentity *peer, int create)
1541 {
1542   struct RIL_Peer_Agent *cur;
1543
1544   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1545   {
1546     if (0 == memcmp (peer, &cur->peer, sizeof(struct GNUNET_PeerIdentity)))
1547     {
1548       return cur;
1549     }
1550   }
1551
1552   if (create)
1553   {
1554     cur = agent_init (solver, peer);
1555     GNUNET_CONTAINER_DLL_insert_tail(solver->agents_head, solver->agents_tail, cur);
1556     return cur;
1557   }
1558   return NULL ;
1559 }
1560
1561 /**
1562  * Determine whether at least the minimum bandwidth is set for the network. Otherwise the network is
1563  * considered inactive and not used. Addresses in an inactive network are ignored.
1564  *
1565  * @param solver solver handle
1566  * @param network the network type
1567  * @return whether or not the network is considered active
1568  */
1569 static int
1570 ril_network_is_active (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
1571 {
1572   struct RIL_Network *net;
1573   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1574
1575   net = ril_get_network (solver, network);
1576   return net->bw_out_available >= min_bw;
1577 }
1578
1579 /**
1580  * Cuts a slice out of a vector of elements. This is used to decrease the size of the matrix storing
1581  * the reward function approximation. It copies the memory, which is not cut, to the new vector,
1582  * frees the memory of the old vector, and redirects the pointer to the new one.
1583  *
1584  * @param old pointer to the pointer to the first element of the vector
1585  * @param element_size byte size of the vector elements
1586  * @param hole_start the first element to cut out
1587  * @param hole_length the number of elements to cut out
1588  * @param old_length the length of the old vector
1589  */
1590 static void
1591 ril_cut_from_vector (void **old,
1592     size_t element_size,
1593     unsigned int hole_start,
1594     unsigned int hole_length,
1595     unsigned int old_length)
1596 {
1597   char *tmpptr;
1598   char *oldptr = (char *) *old;
1599   size_t size;
1600   unsigned int bytes_before;
1601   unsigned int bytes_hole;
1602   unsigned int bytes_after;
1603
1604   GNUNET_assert(old_length > hole_length);
1605   GNUNET_assert(old_length >= (hole_start + hole_length));
1606
1607   size = element_size * (old_length - hole_length);
1608
1609   bytes_before = element_size * hole_start;
1610   bytes_hole = element_size * hole_length;
1611   bytes_after = element_size * (old_length - hole_start - hole_length);
1612
1613   if (0 == size)
1614   {
1615     tmpptr = NULL;
1616   }
1617   else
1618   {
1619     tmpptr = GNUNET_malloc (size);
1620     memcpy (tmpptr, oldptr, bytes_before);
1621     memcpy (tmpptr + bytes_before, oldptr + (bytes_before + bytes_hole), bytes_after);
1622   }
1623   if (NULL != *old)
1624   {
1625     GNUNET_free(*old);
1626   }
1627   *old = (void *) tmpptr;
1628 }
1629
1630 /*
1631  *  Solver API functions
1632  *  ---------------------------
1633  */
1634
1635 /**
1636  * Change relative preference for quality in solver
1637  *
1638  * @param solver the solver handle
1639  * @param peer the peer to change the preference for
1640  * @param kind the kind to change the preference
1641  * @param pref_rel the normalized preference value for this kind over all clients
1642  */
1643 void
1644 GAS_ril_address_change_preference (void *solver,
1645     const struct GNUNET_PeerIdentity *peer,
1646     enum GNUNET_ATS_PreferenceKind kind,
1647     double pref_rel)
1648 {
1649   LOG(GNUNET_ERROR_TYPE_DEBUG,
1650       "API_address_change_preference() Preference '%s' for peer '%s' changed to %.2f \n",
1651       GNUNET_ATS_print_preference_type (kind), GNUNET_i2s (peer), pref_rel);
1652
1653   ril_step (solver);
1654 }
1655
1656 /**
1657  * Entry point for the plugin
1658  *
1659  * @param cls pointer to the 'struct GNUNET_ATS_PluginEnvironment'
1660  */
1661 void *
1662 libgnunet_plugin_ats_ril_init (void *cls)
1663 {
1664   struct GNUNET_ATS_PluginEnvironment *env = cls;
1665   struct GAS_RIL_Handle *solver = GNUNET_new (struct GAS_RIL_Handle);
1666   struct RIL_Network * cur;
1667   int c;
1668   char *string;
1669
1670   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_init() Initializing RIL solver\n");
1671
1672   GNUNET_assert(NULL != env);
1673   GNUNET_assert(NULL != env->cfg);
1674   GNUNET_assert(NULL != env->stats);
1675   GNUNET_assert(NULL != env->bandwidth_changed_cb);
1676   GNUNET_assert(NULL != env->get_preferences);
1677   GNUNET_assert(NULL != env->get_property);
1678
1679   if (GNUNET_OK
1680       != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MIN",
1681           &solver->parameters.step_time_min))
1682   {
1683     solver->parameters.step_time_min = RIL_DEFAULT_STEP_TIME_MIN;
1684   }
1685   if (GNUNET_OK
1686       != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MAX",
1687           &solver->parameters.step_time_max))
1688   {
1689     solver->parameters.step_time_max = RIL_DEFAULT_STEP_TIME_MAX;
1690   }
1691   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_ALGORITHM", &string))
1692   {
1693     solver->parameters.algorithm = !strcmp (string, "SARSA") ? RIL_ALGO_SARSA : RIL_ALGO_Q;
1694     GNUNET_free (string);
1695   }
1696   else
1697   {
1698     solver->parameters.algorithm = RIL_DEFAULT_ALGORITHM;
1699   }
1700   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_DISCOUNT_BETA", &string))
1701   {
1702     solver->parameters.beta = strtod (string, NULL);
1703     GNUNET_free (string);
1704   }
1705   else
1706   {
1707     solver->parameters.beta = RIL_DEFAULT_DISCOUNT_BETA;
1708   }
1709   if (GNUNET_OK
1710       == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_GRADIENT_STEP_SIZE", &string))
1711   {
1712     solver->parameters.alpha = strtod (string, NULL);
1713     GNUNET_free (string);
1714   }
1715   else
1716   {
1717     solver->parameters.alpha = RIL_DEFAULT_GRADIENT_STEP_SIZE;
1718   }
1719   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_TRACE_DECAY", &string))
1720   {
1721     solver->parameters.lambda = strtod (string, NULL);
1722     GNUNET_free (string);
1723   }
1724   else
1725   {
1726     solver->parameters.lambda = RIL_DEFAULT_TRACE_DECAY;
1727   }
1728   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_EXPLORE_RATIO", &string))
1729   {
1730     solver->parameters.explore_ratio = strtod (string, NULL);
1731     GNUNET_free (string);
1732   }
1733   else
1734   {
1735     solver->parameters.explore_ratio = RIL_DEFAULT_EXPLORE_RATIO;
1736   }
1737   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_GLOBAL_REWARD_SHARE", &string))
1738   {
1739     solver->parameters.reward_global_share = strtod (string, NULL);
1740     GNUNET_free (string);
1741   }
1742   else
1743   {
1744     solver->parameters.reward_global_share = RIL_DEFAULT_GLOBAL_REWARD_SHARE;
1745   }
1746
1747   env->sf.s_add = &GAS_ril_address_add;
1748   env->sf.s_address_update_property = &GAS_ril_address_property_changed;
1749   env->sf.s_address_update_session = &GAS_ril_address_session_changed;
1750   env->sf.s_address_update_inuse = &GAS_ril_address_inuse_changed;
1751   env->sf.s_address_update_network = &GAS_ril_address_change_network;
1752   env->sf.s_get = &GAS_ril_get_preferred_address;
1753   env->sf.s_get_stop = &GAS_ril_stop_get_preferred_address;
1754   env->sf.s_pref = &GAS_ril_address_change_preference;
1755   env->sf.s_feedback = &GAS_ril_address_preference_feedback;
1756   env->sf.s_del = &GAS_ril_address_delete;
1757   env->sf.s_bulk_start = &GAS_ril_bulk_start;
1758   env->sf.s_bulk_stop = &GAS_ril_bulk_stop;
1759
1760   solver->plugin_envi = env;
1761   solver->networks_count = env->network_count;
1762   solver->network_entries = GNUNET_malloc (env->network_count * sizeof (struct RIL_Network));
1763   solver->step_count = 0;
1764   solver->global_state_networks = GNUNET_malloc (solver->networks_count * RIL_FEATURES_NETWORK_COUNT * sizeof (double));
1765
1766   for (c = 0; c < env->network_count; c++)
1767   {
1768     cur = &solver->network_entries[c];
1769     cur->type = env->networks[c];
1770     cur->bw_in_available = env->in_quota[c];
1771     cur->bw_out_available = env->out_quota[c];
1772   }
1773
1774   solver->step_next_task_id = GNUNET_SCHEDULER_add_delayed (
1775       GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_get_millisecond_ (), 1000),
1776       &ril_step_scheduler_task, solver);
1777   solver->step_task_pending = GNUNET_YES;
1778
1779   return solver;
1780 }
1781
1782 /**
1783  * Exit point for the plugin
1784  *
1785  * @param cls the solver handle
1786  */
1787 void *
1788 libgnunet_plugin_ats_ril_done (void *cls)
1789 {
1790   struct GAS_RIL_Handle *s = cls;
1791   struct RIL_Peer_Agent *cur_agent;
1792   struct RIL_Peer_Agent *next_agent;
1793
1794   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_done() Shutting down RIL solver\n");
1795
1796   cur_agent = s->agents_head;
1797   while (NULL != cur_agent)
1798   {
1799     next_agent = cur_agent->next;
1800     GNUNET_CONTAINER_DLL_remove(s->agents_head, s->agents_tail, cur_agent);
1801     agent_die (s, cur_agent);
1802     cur_agent = next_agent;
1803   }
1804
1805   if (s->step_task_pending)
1806   {
1807     GNUNET_SCHEDULER_cancel (s->step_next_task_id);
1808   }
1809   GNUNET_free(s->network_entries);
1810   GNUNET_free(s->global_state_networks);
1811   GNUNET_free(s);
1812
1813   return NULL ;
1814 }
1815
1816 /**
1817  * Add a new address for a peer to the solver
1818  *
1819  * The address is already contained in the addresses hashmap!
1820  *
1821  * @param solver the solver Handle
1822  * @param address the address to add
1823  * @param network network type of this address
1824  */
1825 void
1826 GAS_ril_address_add (void *solver, struct ATS_Address *address, uint32_t network)
1827 {
1828   struct GAS_RIL_Handle *s = solver;
1829   struct RIL_Peer_Agent *agent;
1830   struct RIL_Address_Wrapped *address_wrapped;
1831   struct RIL_Network *net;
1832   unsigned int m_new;
1833   unsigned int m_old;
1834   unsigned int n_new;
1835   unsigned int n_old;
1836   int i;
1837   unsigned int zero;
1838
1839   LOG (GNUNET_ERROR_TYPE_DEBUG, "API_address_add()\n");
1840
1841   net = ril_get_network (s, network);
1842   address->solver_information = net;
1843
1844   if (!ril_network_is_active (s, network))
1845   {
1846     LOG(GNUNET_ERROR_TYPE_DEBUG,
1847         "API_address_add() Did not add %s address %s for peer '%s', network does not have enough bandwidth\n",
1848         address->plugin, address->addr, GNUNET_i2s (&address->peer));
1849     return;
1850   }
1851
1852   agent = ril_get_agent (s, &address->peer, GNUNET_YES);
1853
1854   //add address
1855   address_wrapped = GNUNET_malloc (sizeof (struct RIL_Address_Wrapped));
1856   address_wrapped->address_naked = address;
1857   GNUNET_CONTAINER_DLL_insert_tail(agent->addresses_head, agent->addresses_tail, address_wrapped);
1858
1859   //increase size of W
1860   m_new = agent->m + RIL_FEATURES_ADDRESS_COUNT;
1861   m_old = agent->m;
1862   n_new = agent->n + 1;
1863   n_old = agent->n;
1864
1865   GNUNET_array_grow(agent->W, agent->n, n_new);
1866   for (i = 0; i < n_new; i++)
1867   {
1868     if (i < n_old)
1869     {
1870       agent->m = m_old;
1871       GNUNET_array_grow(agent->W[i], agent->m, m_new);
1872     }
1873     else
1874     {
1875       zero = 0;
1876       GNUNET_array_grow(agent->W[i], zero, m_new);
1877     }
1878   }
1879
1880   //increase size of old state vector
1881   agent->m = m_old;
1882   GNUNET_array_grow(agent->s_old, agent->m, m_new);
1883
1884   agent->m = m_old;
1885   GNUNET_array_grow(agent->e, agent->m, m_new);
1886
1887   ril_try_unblock_agent(s, agent, GNUNET_NO);
1888
1889   ril_step (s);
1890
1891   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_add() Added %s %s address %s for peer '%s'\n",
1892       address->active ? "active" : "inactive", address->plugin, address->addr,
1893       GNUNET_i2s (&address->peer));
1894 }
1895
1896 /**
1897  * Delete an address in the solver
1898  *
1899  * The address is not contained in the address hashmap anymore!
1900  *
1901  * @param solver the solver handle
1902  * @param address the address to remove
1903  * @param session_only delete only session not whole address
1904  */
1905 void
1906 GAS_ril_address_delete (void *solver, struct ATS_Address *address, int session_only)
1907 {
1908   struct GAS_RIL_Handle *s = solver;
1909   struct RIL_Peer_Agent *agent;
1910   struct RIL_Address_Wrapped *address_wrapped;
1911   int address_was_used = address->active;
1912   int address_index;
1913   unsigned int m_new;
1914   unsigned int n_new;
1915   int i;
1916   struct RIL_Network *net;
1917   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1918
1919   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_delete() Delete %s%s %s address %s for peer '%s'\n",
1920       session_only ? "session for " : "", address->active ? "active" : "inactive", address->plugin,
1921       address->addr, GNUNET_i2s (&address->peer));
1922
1923   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
1924   if (NULL == agent)
1925   {
1926     net = address->solver_information;
1927     GNUNET_assert(!ril_network_is_active (s, net->type));
1928     LOG(GNUNET_ERROR_TYPE_DEBUG,
1929         "No agent allocated for peer yet, since address was in inactive network\n");
1930     return;
1931   }
1932
1933   address_index = agent_address_get_index (agent, address);
1934   address_wrapped = agent_address_get (agent, address);
1935
1936   if (NULL == address_wrapped)
1937   {
1938     net = address->solver_information;
1939     GNUNET_assert(!ril_network_is_active (s, net->type));
1940     LOG(GNUNET_ERROR_TYPE_DEBUG,
1941         "Address not considered by agent, address was in inactive network\n");
1942     return;
1943   }
1944
1945   GNUNET_CONTAINER_DLL_remove(agent->addresses_head, agent->addresses_tail, address_wrapped);
1946   GNUNET_free(address_wrapped);
1947
1948   //decrease W
1949   m_new = agent->m - RIL_FEATURES_ADDRESS_COUNT;
1950   n_new = agent->n - 1;
1951
1952   for (i = 0; i < agent->n; i++)
1953   {
1954     ril_cut_from_vector ((void **) &agent->W[i], sizeof(double),
1955         ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1956             + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1957   }
1958   GNUNET_free(agent->W[RIL_ACTION_TYPE_NUM + address_index]);
1959   ril_cut_from_vector ((void **) &agent->W, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index,
1960       1, agent->n);
1961   //correct last action
1962   if (agent->a_old > (RIL_ACTION_TYPE_NUM + address_index))
1963   {
1964     agent->a_old -= 1;
1965   }
1966   else if (agent->a_old == (RIL_ACTION_TYPE_NUM + address_index))
1967   {
1968     agent->a_old = RIL_ACTION_INVALID;
1969   }
1970   //decrease old state vector and eligibility vector
1971   ril_cut_from_vector ((void **) &agent->s_old, sizeof(double),
1972       ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1973           + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1974   ril_cut_from_vector ((void **) &agent->e, sizeof(double),
1975       ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1976           + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1977   agent->m = m_new;
1978   agent->n = n_new;
1979
1980   LOG(GNUNET_ERROR_TYPE_DEBUG, "address was used: %s\n", address_was_used ? "yes" : "no");
1981
1982   if (address_was_used)
1983   {
1984     if (NULL != agent->addresses_head) //if peer has an address left, use it
1985     {
1986       LOG(GNUNET_ERROR_TYPE_DEBUG, "address left: %s\n",
1987           agent->addresses_head->address_naked->addr);
1988
1989       envi_set_active_suggestion (s, agent, agent->addresses_head->address_naked, min_bw, min_bw,
1990           GNUNET_NO);
1991     }
1992     else
1993     {
1994       LOG(GNUNET_ERROR_TYPE_DEBUG, "no address left => disconnect\n");
1995
1996       envi_set_active_suggestion (s, agent, NULL, 0, 0, GNUNET_NO);
1997     }
1998   }
1999
2000   LOG(GNUNET_ERROR_TYPE_DEBUG, "Address deleted: %s\n", address->addr);
2001
2002   ril_step (solver);
2003 }
2004
2005 /**
2006  * Update the properties of an address in the solver
2007  *
2008  * @param solver solver handle
2009  * @param address the address
2010  * @param type the ATSI type in HBO
2011  * @param abs_value the absolute value of the property
2012  * @param rel_value the normalized value
2013  */
2014 void
2015 GAS_ril_address_property_changed (void *solver,
2016     struct ATS_Address *address,
2017     uint32_t type,
2018     uint32_t abs_value,
2019     double rel_value)
2020 {
2021   LOG(GNUNET_ERROR_TYPE_DEBUG,
2022       "API_address_property_changed() Property '%s' for peer '%s' address %s changed "
2023           "to %.2f \n", GNUNET_ATS_print_property_type (type), GNUNET_i2s (&address->peer),
2024       address->addr, rel_value);
2025
2026   ril_step (solver);
2027 }
2028
2029 /**
2030  * Update the session of an address in the solver
2031  *
2032  * NOTE: values in addresses are already updated
2033  *
2034  * @param solver solver handle
2035  * @param address the address
2036  * @param cur_session the current session
2037  * @param new_session the new session
2038  */
2039 void
2040 GAS_ril_address_session_changed (void *solver,
2041     struct ATS_Address *address,
2042     uint32_t cur_session,
2043     uint32_t new_session)
2044 {
2045   /*
2046    * TODO? Future Work: Potentially add session activity as a feature in state vector
2047    */
2048   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_session_changed()\n");
2049 }
2050
2051 /**
2052  * Notify the solver that an address is (not) actively used by transport
2053  * to communicate with a remote peer
2054  *
2055  * NOTE: values in addresses are already updated
2056  *
2057  * @param solver solver handle
2058  * @param address the address
2059  * @param in_use usage state
2060  */
2061 void
2062 GAS_ril_address_inuse_changed (void *solver, struct ATS_Address *address, int in_use)
2063 {
2064   /*
2065    * TODO? Future Work: Potentially add usage variable to state vector
2066    */
2067   LOG(GNUNET_ERROR_TYPE_DEBUG,
2068       "API_address_inuse_changed() Usage for %s address of peer '%s' changed to %s\n",
2069       address->plugin, GNUNET_i2s (&address->peer), (GNUNET_YES == in_use) ? "USED" : "UNUSED");
2070 }
2071
2072 /**
2073  * Notify solver that the network an address is located in has changed
2074  *
2075  * NOTE: values in addresses are already updated
2076  *
2077  * @param solver solver handle
2078  * @param address the address
2079  * @param current_network the current network
2080  * @param new_network the new network
2081  */
2082 void
2083 GAS_ril_address_change_network (void *solver,
2084     struct ATS_Address *address,
2085     uint32_t current_network,
2086     uint32_t new_network)
2087 {
2088   struct GAS_RIL_Handle *s = solver;
2089   struct RIL_Peer_Agent *agent;
2090
2091   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_change_network() Network type changed, moving "
2092       "%s address of peer %s from '%s' to '%s'\n",
2093       (GNUNET_YES == address->active) ? "active" : "inactive", GNUNET_i2s (&address->peer),
2094       GNUNET_ATS_print_network_type (current_network), GNUNET_ATS_print_network_type (new_network));
2095
2096   if (address->active && !ril_network_is_active (solver, new_network))
2097   {
2098     GAS_ril_address_delete (solver, address, GNUNET_NO);
2099     return;
2100   }
2101
2102   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
2103   if (NULL == agent)
2104   {
2105     GNUNET_assert(!ril_network_is_active (solver, current_network));
2106
2107     GAS_ril_address_add (s, address, new_network);
2108     return;
2109   }
2110
2111   address->solver_information = ril_get_network(solver, new_network);
2112 }
2113
2114 /**
2115  * Give feedback about the current assignment
2116  *
2117  * @param solver the solver handle
2118  * @param application the application
2119  * @param peer the peer to change the preference for
2120  * @param scope the time interval for this feedback: [now - scope .. now]
2121  * @param kind the kind to change the preference
2122  * @param score the score
2123  */
2124 void
2125 GAS_ril_address_preference_feedback (void *solver,
2126     void *application,
2127     const struct GNUNET_PeerIdentity *peer,
2128     const struct GNUNET_TIME_Relative scope,
2129     enum GNUNET_ATS_PreferenceKind kind,
2130     double score)
2131 {
2132   LOG(GNUNET_ERROR_TYPE_DEBUG,
2133       "API_address_preference_feedback() Peer '%s' got a feedback of %+.3f from application %s for "
2134           "preference %s for %d seconds\n", GNUNET_i2s (peer), "UNKNOWN",
2135       GNUNET_ATS_print_preference_type (kind), scope.rel_value_us / 1000000);
2136 }
2137
2138 /**
2139  * Start a bulk operation
2140  *
2141  * @param solver the solver
2142  */
2143 void
2144 GAS_ril_bulk_start (void *solver)
2145 {
2146   struct GAS_RIL_Handle *s = solver;
2147
2148   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_bulk_start() lock: %d\n", s->bulk_lock+1);
2149
2150   s->bulk_lock++;
2151 }
2152
2153 /**
2154  * Bulk operation done
2155  *
2156  * @param solver the solver handle
2157  */
2158 void
2159 GAS_ril_bulk_stop (void *solver)
2160 {
2161   struct GAS_RIL_Handle *s = solver;
2162
2163   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_bulk_stop() lock: %d\n", s->bulk_lock-1);
2164
2165   if (s->bulk_lock < 1)
2166   {
2167     GNUNET_break(0);
2168     return;
2169   }
2170   s->bulk_lock--;
2171
2172   if (0 < s->bulk_changes)
2173   {
2174     ril_step (solver);
2175     s->bulk_changes = 0;
2176   }
2177 }
2178
2179 /**
2180  * Tell solver to notify ATS if the address to use changes for a specific
2181  * peer using the bandwidth changed callback
2182  *
2183  * The solver must only notify about changes for peers with pending address
2184  * requests!
2185  *
2186  * @param solver the solver handle
2187  * @param peer the identity of the peer
2188  */
2189 const struct ATS_Address *
2190 GAS_ril_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
2191 {
2192   /*
2193    * activate agent, return currently chosen address
2194    */
2195   struct GAS_RIL_Handle *s = solver;
2196   struct RIL_Peer_Agent *agent;
2197
2198   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_get_preferred_address()\n");
2199
2200   agent = ril_get_agent (s, peer, GNUNET_YES);
2201
2202   agent->is_active = GNUNET_YES;
2203   envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, agent->bw_out, GNUNET_YES);
2204
2205   ril_try_unblock_agent(solver, agent, GNUNET_YES);
2206
2207   if (agent->address_inuse)
2208   {
2209     LOG(GNUNET_ERROR_TYPE_DEBUG,
2210         "API_get_preferred_address() Activated agent for peer '%s' with %s address %s\n",
2211         GNUNET_i2s (peer), agent->address_inuse->plugin, agent->address_inuse->addr);
2212   }
2213   else
2214   {
2215     LOG(GNUNET_ERROR_TYPE_DEBUG,
2216         "API_get_preferred_address() Activated agent for peer '%s', but no address available\n",
2217         GNUNET_i2s (peer));
2218   }
2219
2220   return agent->address_inuse;
2221 }
2222
2223 /**
2224  * Tell solver stop notifying ATS about changes for this peers
2225  *
2226  * The solver must only notify about changes for peers with pending address
2227  * requests!
2228  *
2229  * @param solver the solver handle
2230  * @param peer the peer
2231  */
2232 void
2233 GAS_ril_stop_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
2234 {
2235   struct GAS_RIL_Handle *s = solver;
2236   struct RIL_Peer_Agent *agent;
2237
2238   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_stop_get_preferred_address()");
2239
2240   agent = ril_get_agent (s, peer, GNUNET_NO);
2241
2242   if (NULL == agent)
2243   {
2244     GNUNET_break(0);
2245     return;
2246   }
2247   if (GNUNET_NO == agent->is_active)
2248   {
2249     GNUNET_break(0);
2250     return;
2251   }
2252
2253   agent->is_active = GNUNET_NO;
2254
2255   envi_set_active_suggestion (s, agent, agent->address_inuse, agent->bw_in, agent->bw_out,
2256       GNUNET_YES);
2257
2258   ril_step (s);
2259
2260   LOG(GNUNET_ERROR_TYPE_DEBUG,
2261       "API_stop_get_preferred_address() Paused agent for peer '%s' with %s address\n",
2262       GNUNET_i2s (peer), agent->address_inuse->plugin);
2263 }
2264
2265 /* end of libgnunet_plugin_ats_ril.c */